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

PPSC Unit 5

The document discusses functions in C programming. It defines functions and their key parts, including function prototypes, definitions, calls, parameters, and return values. It also describes the four main categories of functions: 1) no arguments, no return value, 2) no arguments, return value, 3) arguments, no return value, and 4) arguments and return value. Modular programming with functions improves code reusability, readability, and enables dividing work among programmers.

Uploaded by

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

PPSC Unit 5

The document discusses functions in C programming. It defines functions and their key parts, including function prototypes, definitions, calls, parameters, and return values. It also describes the four main categories of functions: 1) no arguments, no return value, 2) no arguments, return value, 3) arguments, no return value, and 4) arguments and return value. Modular programming with functions improves code reusability, readability, and enables dividing work among programmers.

Uploaded by

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

UNIT-V

FUNCTIONS
INTRODUCTION

“Modular programming is the process of subdividing a computer program into separate sub-
programs.” A module is a separate software component. It can often be used in a variety of
applications and functions with other components of the system. Similar functions are grouped in
the same unit of programming code and separate functions are developed as separate units of code
so that the code can be reused by other applications.Object-oriented programming (OOP) is
compatible with the modular programming concept to a large extent. Modular programming enables
multiple programmers to divide up the work and debug pieces of the program independently.

Function and Parameter Declarations:

Function definition: A Function is a self-contained block of statement that performs a specific task
when called. A function is also called as sub program or procedure or subroutine.
Every C Program can be thought of as a collection of these functions. Function is a set of
instructions to carry out a particular task. Function after its execution returns a single value.

Designing Structured Programs in C


Structured programming is a programming technique in which a larger program is divided into
smaller subprograms to make it easy to understand, easy to implement and makes the code reusable,
etc. Structured programming enables code reusability. Code reusability is a method of writing code
once and using it many times. Using a structured programming technique, we write the code once
and use it many times. Structured programming also makes the program easy to understand,
improves the quality of the program, easy to implement and reduces time.
In C, the structured programming can be designed using functions concept. Using functions
concept, we can divide the larger program into smaller subprograms and these subprograms are
implemented individually. Every subprogram or function in C is executed individually.

FUNCTIONS IN C
Generally, the functions are classified into two types:
1. Standard functions
2. User-defined functions.
The Standard functions are also called library functions or built-in functions. All standard functions,
such as sqrt(), abs(), log(), sin() etc. are provided in the library of function. But, most of the
applications need other functions than those available in the software; those are known as user-
defined functions.
Advantages of functions: Several advantages of dividing the program into functions include:
 Modularity
 Reduction in code redundancy
 Enabling code reuse
 Better readability
Parts of a function: A function has the following parts:
 Function prototype declaration.
 Function definition.
 Function call.
 Actual arguments and Formal arguments.
 The return statement.
Function Declaration:Function prototype declaration consist function return type, function name,
and argument list. A function must be declared before it is used
Syntax:return_typefunction_name(parameter_list);
parameter_list: type param1,type param2,type param3, etc
Examples: double sqrt(double);
int func1();
void func2(char c);

Function Definition also known as function implementation, means composing a function. Every
Function definition consists of two Parts:
 Header of the function,
 Body of the function.
Syntax :return_typefunction_name(parameter_list)
{
// Function body
}
The body of a function consists of a set of statements enclosed within braces. The return statement
is used to return the result of the computations done in the calledfunction and/or to return the
program control back to the calling function. A function can be defined in any part of the program
text or within a library
Example: void welcome( )
{ Function header
printf(“hello world\n”); //Function body
}

Function Call (Calling function):


A function call has the following syntax:
function_name(<argument list>);
Example: sum(a,b);
Program: C Program to illustrate functions actual arguments
#include<stdio.h> a,b are different
int sum(int,int); //function prototype from formal
main() //main function
arguments a,b in
{
int a=10,b=20,c; both the main() and
c=sum(a,b); //calling function with actual arguments sum() functions
printf("sum of a,b is %d",c);
}
int sum(int a, int b) //called function with formal arguments
{
return(a+b);
}
o/p: sum of a,b is 30

Types/Categories of functions:
All C functions can be called either with arguments or without arguments in a C program. These
functions may or may not return values to the calling function. Functions can be divided into 4
categories:
1. A function with no arguments and no return value
2. A function with no arguments and a return value
3. A function with an argument/parameter or arguments and no return value
4. A function with arguments and a return value
C functions aspects syntax
function declaration:int function ( int );
function call: function ( a );
function definition:
int function( int a )
With arguments and with return values
{
statements;
return a;
}
function declaration:void function ( int );
function call: function( a );
function definition:
With arguments and without return values void function( int a )
{
statements;
}

function declaration:void function();


function call: function();
function definition:
Without arguments and without return values void function()
{
statements;
}

NOTE:
 If the return data type of a function is “void”, then, it can’t return any values to the calling
function.
 If the return data type of the function is other than void such as “int, float, double etc”, then, it
can return values to the calling function.

1. A function with no arguments and no return value:


 Called function does not have any arguments
 Not able to get any value from the calling function
 Not returning any value
 There is no data transfer between the calling function and called function.
Example :
#include<stdio.h>
void welcome(); //function prototype declaration
int main() // calling function
{
welcome(); //function call -- without arguments
return 0;
}
void welcome() //called function
{
printf("Hi students..!"); //function body -- no return value
}
OUTPUT:
Hi students..!
2.A function with no arguments and a return value:
 Does not get any value from the calling function
 Can give a return value to calling program
Example :
#include <stdio.h>
int send();
int main()
{
int x;
x=send();
printf("\nYou entered : %d",x);
return 0;
}
int send()
{
int n;
printf("\nEnter a number: ");
scanf("%d",&n);
return n;
}
OUTPUT:
Enter a number: 5
You entered: 5

3.A function with an argument(s) and returning no value:


 A function has argument(s).
 A calling function can pass values to function called, but calling function not receives any
value.
 Data is transferred from calling function to the called function but no data is transferred
from the called function to the calling function.
 Generally Output is printed in the Called function.
Example:
#include<stdio.h>
void add(int x, int y);
int main()
{
add(30,15);
add(63,49);
return 0;;
}
void add(int a, int b)
{
int result;
result = a+b;
printf("Sum of %d and %d is %d\n",a,b,result);
}
OUTPUT
Sum of 30 and 15 is 45
Sum of 63 and 49 is 112

4.A function with arguments and return value:


 Argument are passed by calling function to the called function
 Called function return value to the calling function
 Data returned by the function can be used later in our program for further calculation
 Mostly used in programming because it can two way communication
Example:
#include <stdio.h>
int add(int x, int y);
int main()
{
int z;
z=add(11,22);
printf("Result %d\n", add(30,55));
printf("Result %d\n", z);
return 0;
}
int add(int a, int b)
{
int result;
result = a + b;
return (result);
}
OUTPUT:
Result = 85
Result = 33

Other examples programs for function types(same above topic with another examples)

//Function without Parameters and without Return value


#include<stdio.h>
#include<conio.h>

int main(){
void addition() ; // function declaration

addition() ; // function call

getch() ;
}
void addition() // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
printf("Sum = %d", num1+num2 ) ;
}
o/p:
Enter any two integer numbers : 2
3
Sum = 5
//Function with Parameters and without Return value
#include<stdio.h>
#include<conio.h>
int main()
{
int num1, num2 ;
void addition(int, int) ; // function declaration
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
addition(num1, num2) ; // function call
getch() ;
}
void addition(int a, int b) // function definition
{
printf("Sum = %d", a+b ) ;
}
o/p:
Enter any two integer numbers : 2
3
Sum = 5

//Function without Parameters and with Return value


#include<stdio.h>
#include<conio.h>

int main()
{
int result ;
int addition() ; // function declaration

result = addition() ; // function call


printf("Sum = %d", result) ;
getch() ;
}
int addition() // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
return (num1+num2) ;
}
o/p:
Enter any two integer numbers : 2
3
Sum = 5

//Function with Parameters and with Return value


#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) ;
}
int addition(int a, int b) // function definition
{
return (a+b) ;
}
o/p:
Enter any two integer numbers : 2
3
Sum = 5

Parameter Passing Mechanism:


There are two ways that a C function can be called from a program. They are,
 Call by Value/ Pass by Value
 Call by Reference / Pass by Reference
Call by Value: In call by value method, the value of the variable is passed to the function as
parameter. The value of the actual parameter cannot be modified by formal parameter. Different
Memory is allocated for both actual and formal parameters. Because, value of actual parameter is
copied to formal parameter.
Example:
#include<stdio.h>
void swap(int , int );
int main()
{
int a = 22, b = 44;
printf("\nValues before swap a = %d and b = %d", a, b);
swap(a,b);
printf(" \nValues after swap a = %d and b = %d", a, b); //no effect in main() a,b values
return 0;
}
void swap(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
}
OUTPUT:
Values before swap a =22 and b = 44
Values after swap a =22 and b = 44

Cal by value example 2 :

#include <stdio.h>
void swap(int , int); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and
b in main
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual parameters
do not change by changing the formal parameters in call by value, a = 10, b = 20
}
void swap (int a, int b)
{
int temp;
temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters, a = 20, b
= 10
}
o/p:
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20

Call by Reference: In call by reference method, the address of the variable is passed to the function
as parameter. The value of the actual parameter can be modified by formal parameter. Same
memory is used for both actual and formal parameters since only address is used by both
parameters.
Example:
#include<stdio.h>
void swap(int *, int *);
int main()
{
int a = 22, b = 44;
printf("\nValues before swap a = %d and b = %d", a, b);
swap(&a,&b); //passing address(s) to the function
printf(" \nValues after swap a = %d and b = %d", a, b);
return 0;
}
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
OUTPUT:
Values before swap a =22 and b = 44
Values after swap a =44 and b = 22
INTER FUNCTION COMMUNICATION

When a function gets executed in the program, the execution control is transferred from calling a
function to called function and executes function definition, and finally comes back to the calling
function. In this process, both calling and called functions have to communicate with each other to
exchange information. The process of exchanging information between calling and called functions
is called inter-function communication.
In C, the inter function communication is classified as follows...

 Downward Communication
 Upward Communication
 Bi-directional Communication
Downward Communication
In this type of inter function communication, the data is transferred from calling function to called
function but not from called function to calling function. The functions with parameters and without
return value are considered under downward communication. In the case of downward
communication, the execution control jumps from calling function to called function along with
parameters and executes the function definition,and finally comes back to the calling function
without any return value. For example consider the following program...

Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void addition(int, int) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
addition(num1, num2) ; // calling function
getch() ;
}
void addition(int a, int b) // called function
{
printf("SUM = %d", a+b) ;

}
o/p:sum=30
Upward Communication
In this type of inter-function communication, the data is transferred from called function to calling-
function but not from calling-function to called-function. The functions without parameters and
with return value are considered under upward communication. In the case of upward
communication, the execution control jumps from calling-function to called-function without
parameters and executes the function definition, and finally comes back to the calling function
along with a return value. For example, consider the following program...
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int result ;
int addition() ; // function declaration
clrscr() ;
result = addition() ; // calling function
printf("SUM = %d", result) ;
getch() ;
}
int addition() // called function
{
int num1, num2 ;
num1 = 10;
num2 = 20;
return (num1+num2) ;
}
Output: sum=30

Bi - Directional Communication
In this type of inter-function communication, the data is transferred from calling-function to called
function and also from called function to calling-function. The functions with parameters and with
return value are considered under bi-directional communication. In the case of bi-directional
communication, the execution control jumps from calling-function to called function along with
parameters and executes the function definition and finally comes back to the calling function along
with a return value. For example, consider the following program...

Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int num1, num2, result ;
int addition(int, int) ; // function declaration
num1 = 10 ;
num2 = 20 ;
result = addition(num1, num2) ; // calling function
printf("SUM = %d", result) ;
getch() ;
}
int addition(int a, int b) // called function
{
return (a+b) ;
}
Output: Sum=30

Standard Functions in C
The standard functions are built-in functions. In C programming language, the standard functions
are declared in header files and defined in .dll files. In simple words, the standard functions can be
defined as "the ready made functions defined by the system to make coding more easy". The
standard functions are also called as library functions or pre-defined functions.
In C when we use standard functions, we must include the respective header file
using #include statement. For example, the function printf() is defined in header
file stdio.h (Standard Input Output header file). When we use printf() in our program, we must
include stdio.h header file using #include<stdio.h> statement.
Header Example
File Purpose Functions
stdio.h Provides functions to perform standard I/O operations printf(), scanf()

conio.h Provides functions to perform console I/O operations clrscr(), getch()

math.h Provides functions to perform mathematical operations sqrt(), pow()

string.h Provides functions to handle string data values strlen(), strcpy()

stdlib.h Provides functions to perform general functions/td> calloc(), malloc()

time.h Provides functions to perform operations on time and date time(), localtime()

ctype.h Provides functions to perform - testing and mapping of character data isalpha(), islower()
values
Function Description
This function returns the absolute value of an integer. The absolute value of a
abs ( ) number is always positive. Only integer values are supported in C.
This function returns the nearest integer which is less than or equal to the
floor ( ) argument passed to this function.
This function returns the nearest integer value of the float/double/long
double argument passed to this function. If decimal value is from “.1 to .5”, it
returns integer value less than the argument. If decimal value is from “.6 to .9”,
round ( ) it returns the integer value greater than the argument.
This function returns nearest integer value which is greater than or equal to the
ceil ( ) argument passed to this function.
sin ( ) This function is used to calculate sine value.
cos ( ) This function is used to calculate cosine.
tan ( ) This function is used to calculate tangent.
sqrt ( ) This function is used to find square root of the argument passed to this function.
pow ( ) This is used to find the power of the given number.
Header Example
File Purpose Functions
This function truncates the decimal value from floating point value and returns
trunc ( ) integer value.

 abs( ) function in C returns the absolute value of an integer. The absolute value of a number
is always positive. Only integer values are supported in C.
 “stdlib.h” header file supports abs( ) function in C language. Syntax for abs( ) function in C
is given below.
int abs ( int n );
Example :abs
#include <stdio.h>
#include <stdlib.h>
int main()
{
int m = abs(200); // m is assigned to 200
int n = abs(-400); // n is assigned to -400
printf("Absolute value of m = %d\n", m);
printf("Absolute value of n = %d \n",n);
return 0;
}
Absolute value of m=200
Absolute value of n = 400

Example :floor

#include <stdio.h>
#include <math.h>
int main()
{
float i=5.1, j=5.9, k=-5.4, l=-6.9;
printf("floor of %f is %f\n", i, floor(i));
printf("floor of %f is %f\n", j, floor(j));
printf("floor of %f is %f\n", k, floor(k));
printf("floor of %f is %f\n", l, floor(l));
return 0;
}
floor of 5.100000 is 5.000000
floor of 5.900000 is 5.000000
floor of -5.400000 is -6.000000
floor of -6.900000 is -7.000000

Example :round
#include <stdio.h>
#include <math.h>
int main()
{
float i=5.4, j=5.6;
printf("round of %f is %f\n", i, round(i));
printf("round of %f is %f\n", j, round(j));
return 0;
}
round of 5.400000 is 5.000000
round of 5.600000 is 6.000000

Example :ceil

#include <stdio.h>
#include <math.h>
int main()
{
float i=5.4, j=5.6;
printf("ceil of %f is %f\n", i, ceil(i));
printf("ceil of %f is %f\n", j, ceil(j));
return 0;
}
o/p: ceil of 5.400000 is 6.000000
ceil of 5.600000 is 6.000000

Example :square

#include <stdio.h>
#include <math.h>

int main()
{
printf ("sqrt of 16 = %f\n", sqrt (16) );
printf ("sqrt of 2 = %f\n", sqrt (2) );
return 0;
}
sqrt of 16 = 4.000000
sqrt of 2 = 1.414214
Example :pow
#include <stdio.h>
#include <math.h>

int main()
{
printf ("2 power 4 = %f\n", pow (2.0, 4.0) );
printf ("5 power 3 = %f\n", pow (5, 3) );
return 0;
}
OUTPUT:
2 power 4 = 16.000000
5 power 3 = 125.000000

EXAMPLE PROGRAM FOR SIN(), COS(), TAN(), EXP() AND LOG() IN C:

#include <stdio.h>
#include <math.h>
int main()
{
float i = 0.314;
float j = 0.25;
float k = 6.25;
float sin_value = sin(i);
float cos_value = cos(i);
float tan_value = tan(i);
float sinh_value = sinh(j);
float cosh_value = cosh(j);
float tanh_value = tanh(j);
float log_value = log(k);
float log10_value = log10(k);
float exp_value = exp(k);

printf("The value of sin(%f) : %f \n", i, sin_value);


printf("The value of cos(%f) : %f \n", i, cos_value);
printf("The value of tan(%f) : %f \n", i, tan_value);
printf("The value of sinh(%f) : %f \n", j, sinh_value);
printf("The value of cosh(%f) : %f \n", j, cosh_value);
printf("The value of tanh(%f) : %f \n", j, tanh_value);
printf("The value of log(%f) : %f \n", k, log_value);
printf("The value of log10(%f) : %f \n",k,log10_value);
printf("The value of exp(%f) : %f \n",k, exp_value);
return 0;
}
OUTPUT:
The value of sin(0.314000) : 0.308866
The value of cos(0.314000) : 0.951106
The value of tan(0.314000) : 0.324744
The value of sinh(0.250000) : 0.252612
The value of cosh(0.250000) : 1.031413
The value of tanh(0.250000) : 0.244919
The value of log(6.250000) : 1.832582
The value of log10(6.250000) : 0.795880

Recursion - Mathematical Recursion:


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.
Syntax: recursionfunction()
{
recursionfunction(); //calling self function
}
(Or)
int main()
{
recursion();
}
void recursion()
{
recursion(); /* function calls itself */
}
The C programming language supports recursion, i.e., a function to call itself. But 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.
Example factorial program with recursion :
#include<stdio.h>
long factorial(int n)
{
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
int main()
{
int number;
long fact;
printf("Enter a number: ");
scanf("%d", &number);
fact = factorial(number);
printf("Factorial of %d is %ld\n", number, fact);
return 0;
}
enter a number: 2
Factorial of 2 is 2

We can understand the above program of recursive method call by the figure given below:

Factorial with out recursion


#include<stdio.h>
int main()
{
int i,fact=1,number;
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=number;i++){
fact=fact*i;
}
printf("Factorial of %d is: %d",number,fact);
return 0;
}
Enter a number: 5
Factorial of 5 is: 120

Recursion versus Iteration:


S:No. RECURSION ITERATIONS

Recursive function – is a function that is Iterative Instructions –are loop based


1
partially defined by itself repetitions of a process

2 Recursion Uses selection structure Iteration uses repetition structure

Infinite recursion occurs if the recursion


step does not reduce the problem in a An infinite loop occurs with iteration if the
3
manner that converges on some loop-condition test never becomes false
condition.(base case)

Recursion terminates when a base case is Iteration terminates when the loop-
4
recognized condition fails

Recursion is usually slower then iteration Iteration does not use stack so it's faster
5
due to overhead of maintaining stack than recursion
Recursion uses more memory than
6 Iteration consume less memory
iteration

infinite looping uses CPU


7 Infinite recursion can crash the system
cycles repeatedly

8 Recursion makes code smaller Iteration makes code longer

How to pass arrays to a function in C Programming?

In C programming, a single array element or an entire array can be passed to a


function. This can be done for either one-dimensional array or a multi-
dimensional array.
Passing One-dimensional Array in Function:
Single element of an array can be passed in similar manner as passing variable to a function.C
program to pass a single element of an array to function #include <stdio.h>
void display(int age)
{
printf("%d", age);
}
int main() {
int ageArray[] = { 2, 3, 4 };
display(ageArray[2]); //Passing array element OUTPUT:
ageArray[2] only. return 0;
} 4

Passing an entire one-dimensional array to a function:


While passing arrays as arguments to the function, only the name of the array is passed (,i.e,
starting address of memory area is passed as argument).
C program to pass an array containing age of person to a function. This function should find
aver- age age and display the average age in main function.
#include <stdio.h>
float average(float
age[]); int main() {
float avg, age[] = { 23.4, 55, 22.6, 3, 40.5, 18 };
avg = average(age); /* Only name of array is passed as
argument. */ printf("Average age=%.2f", avg);
return 0;
}
float average(float age[])
{
int i;
float avg, sum
= 0.0; for (i = 0;
i < 6; ++i) {
sum += age[i]; OUTPUT:
}
avg = Average age=27.08
(sum / 6);
return
avg;
}

Example 3: Passing two-dimensional arrays


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

// passing 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]);
}
}
}
Output
Enter 4 numbers:
2
3
4
5
Displaying:
2
3
4
5

passing arrays as parameter to function


Now let's see a few examples where we will pass a single array element as argument to a function, a
one dimensional array to a function and a multidimensional array to a function.

Passing a single array element to a function


Let's write a very simple program, where we will declare and define an array of integers in
our main() function and pass one of the array element to a function, which will just print the value
of the element.

#include<stdio.h>

void giveMeArray(int a);

int main()
{
int myArray[] = { 2, 3, 4 };
giveMeArray(myArray[2]); //Passing array element myArray[2] only.
return 0;
}

void giveMeArray(int a)
{
printf("%d", a);
}

o/p:4
Passing a complete One-dimensional array to a function
To understand how this is done, let's write a function to find out average of all the elements of the
array and print it.
We will only send in the name of the array as argument, which is nothing but the address of the
starting element of the array, or we can say the starting memory address.
#include<stdio.h>

float findAverage(int marks[]);

int main()
{
float avg;
int marks[] = {99, 90, 96, 93, 95};
avg = findAverage(marks); // name of the array is passed as argument.
printf("Average marks = %.1f", avg);
return 0;
}

float findAverage(int marks[])


{
int i, sum = 0;
float avg;
for (i = 0; i <= 4; i++) {
sum += marks[i];
}
avg = (sum / 5);
return avg;
}
o/p:
94.6

Passing a Multi-dimensional array to a function


Here again, we will only pass the name of the array as argument.
#include<stdio.h>

void displayArray(int arr[3][3]);

int main()
{
int arr[3][3], i, j;
printf("Please enter 9 numbers for the array: \n");
for (i = 0; i < 3; ++i)
{
for (j = 0; j < 3; ++j)
{
scanf("%d", &arr[i][j]);
}
}
// passing the array as argument
displayArray(arr);
return 0;
}
void displayArray(int arr[3][3])
{
int i, j;
printf("The complete array is: \n");
for (i = 0; i < 3; ++i)
{
// getting cursor to new line
printf("\n");
for (j = 0; j < 3; ++j)
{
// \t is used to provide tab space
printf("%d\t", arr[i][j]);
}
}
}

Please enter 9 numbers for the array:


1
2
3
4
5
6
7
8
9
The complete array is:
123
456
789

How to pass strings to a function in C Programming?


In C programming, array of characters is called a string. A string is terminated by a null character
/0

For example:
"c string tutorial"
Here, "c string tutorial" is a string. When, compilers encounter strings, it appends a null
character /0 at the end of string.

Fig: Memory diagram of strings in C programming

“Strings are just char arrays. So, they can be passed to a function in a similar manner as arrays”.
Example:
#include <stdio.h>
void displayString(char str[]);
int main()
{
char str[50];
printf("Enter string: ");
gets(str);
displayString(str); // Passing string PPS in str to function. return 0;
}
void displayString(char str[])
{
printf("String Output: ");
puts(str);
}
o/p: Enter string: ppsc
String Output: ppsc
Here, string PPS is passed from main() function to user-defined function displayString(). In
func- tion declaration, str[] is the formal argument.

ADDITIONAL PROGRAM WITH SCOPE AND FUNCTIONS

n C programming language, a variable can be declared in three different positions and they are as
follows...
Before the function definition (Global Declaration)
Inside the function or block (Local Declaration)
In the function definition parameters (Formal Parameters)

#include<stdio.h>
#include<conio.h>
int num1, num2 ;
void main(){
void addition() ;
void subtraction() ;
void multiplication() ;
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("num1 = %d, num2 = %d", num1, num2) ;
addition() ;
subtraction() ;
multiplication() ;
getch() ;
}
void addition()
{
int result ;
result = num1 + num2 ;
printf("\naddition = %d", result) ;
}
void subtraction()
{
int result ;
result = num1 - num2 ;
printf("\nsubtraction = %d", result) ;
}
void multiplication()
{
int result ;
result = num1 * num2 ;
printf("\nmultiplication = %d", result) ;
}
o/p:

num1=10,num2=20
addition=10
substraction=-10
multiplication=200

ADDITIONAL EXAMPLES ON ARRAYS WITH FUNCTIONS :


assing array to function using call by value method
As we already know in this type of function call, the actual parameter is copied to the formal
parameters.

#include <stdio.h>
void disp( char ch)
{
printf("%c ", ch);
}
int main()
{
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
for (int x=0; x<10; x++)
{
/* I'm passing each element one by one using subscript*/
disp (arr[x]);
}

return 0;
}

Output:
abcde fghij
Passing array to function using call by reference
When we pass the address of an array while calling a function then this is called function call by
reference. When we pass an address as an argument, the function declaration should have
a pointer as a parameter to receive the passed address.

#include <stdio.h>
void disp( int *num)
{
printf("%d ", *num);
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
for (int i=0; i<10; i++) {
/* Passing addresses of array elements*/
disp (&arr[i]);
}

return 0;
}
Output:
1234567890

How to pass an entire array to a function as an argument?


In the above example, we have passed the address of each array element one by one using a for loop
in C. However you can also pass an entire array to a function like this:
Note: The array name itself is the address of first element of that array. For example if array name is
arr then you can say that arr is equivalent to the &arr[0].

#include <stdio.h>
void myfuncn( int *var1, int var2)
{
/* The pointer var1 is pointing to the first element of
* the array and the var2 is the size of the array. In the
* loop we are incrementing pointer so that it points to
* the next element of the array on each increment.
*
*/
for(int x=0; x<var2; x++)
{
printf("Value of var_arr[%d] is: %d \n", x, *var1);
/*increment pointer for next element fetch*/
var1++;
}
}
int main()
{
int var_arr[] = {11, 22, 33, 44, 55, 66, 77};
myfuncn(var_arr, 7);
return 0;
}
Output:
Value of var_arr[0] is: 11
Value of var_arr[1] is: 22
Value of var_arr[2] is: 33
Value of var_arr[3] is: 44
Value of var_arr[4] is: 55
Value of var_arr[5] is: 66
Value of var_arr[6] is: 77

Another example for passing an array to function


1. #include<stdio.h>
2. int minarray(int arr[],int size){
3. int min=arr[0];
4. int i=0;
5. for(i=1;i<size;i++){
6. if(min>arr[i]){
7. min=arr[i];
8. }
9. }//end of for
10. return min;
11. }//end of function
12.
13. int main(){
14. int i=0,min=0;
15. int numbers[]={4,5,7,3,8,9};//declaration of array
16.
17. min=minarray(numbers,6);//passing array with size
18. printf("minimum number is %d \n",min);
19. return 0;
20. }
Output
minimum number is 3
FILES IN C

FILES:Generally, a file is used to store user data in a computer. In other words, computer stores
the datausing files. we can define a file as follows...
Definition :
File is a collection of data that stored on secondary memory like haddisk of a computer.
File:
It is a place on hard disk where data is stored permanently. A file represents a sequence
of bytes, does not matter if it is a text file or binary file. C programming language
provides access onhigh level functions as well as low level (OS level) calls to handle file
on your storage devices.
Types of files:

C programming language supports two types of files and they are as follows...
 Text Files (or) ASCII Files
 Binary Files

Text File (or) ASCII File - The file that contains ASCII codes of data like digits, alphabets and
symbols is called text file (or) ASCII file.

Binary File - The file that contains data in the form of bytes (0's and 1's) is called as binary file.
Generally, the binary files are compiled version of text files.
Why Files?
In programming, we may require some specific input data to be generated several numbers of times.
Sometimes, it is not enough to only display the data on the console. The data to be displayed may
be very large, and only a limited amount of data can be displayed on the console, and since the
memory is volatile, it is impossible to recover the programmatically generated data again and again.
However, if we need to do so, we may store it onto the local file system which is volatile and can be
accessed every time. Here, comes the need of file handling in C.
Types of Files:

1. Text file
2. Binary File
ASCII Text Files:

 A text file can be a stream of characters that a computer can process sequentially.
 It is processed only in forward direction.
 It is opened for one kind of operation (reading, writing, or appending) at any given time.
 It can read only one character at a time.
 text files are the normal .txt files. You can easily create text files using any simple text editors
such as Notepad.
 When you open those files, you'll see all the contents within the file as plain text. You can easily
edit or delete the contents.
 They take minimum effort to maintain, are easily readable, and provide the least security and
takes bigger storage space.

Binary Files:

 A binary file is collection of bytes.


 In “C” both a byte and a character are equivalent.
 A binary file is also referred to as a character stream, but there are two essential differences.
 Binary files are mostly the .bin files in your computer.
 Instead of storing data in plain text, they store it in the binary form (0's and 1's).
 They can hold a higher amount of data, are not readable easily, and provides better security than
text files.

Modes of file:
Modes of the opening the file:
r - File is opened for reading
w - File is opened for writing
a - File is opened for appending (adding)
r+ - File is opened for both reading & writing
w+ - File is opened for both writing & reading
a+ - File is opened for appending & reading
rt - text file is opened for reading
wt - text file is opened for writing
at - text file is opened for appending
r+t - text file is opened for reading & writing
w+t - text file is opened for both writing & reading
a+t - text file is opened for both appending &reading
rb - binary file is opened for reading
wb - binary file is opened for writing
ab - binary file is opened for appending
r+b - binary file is opened for both reading & writing
w+b - binary file is opened for both writing & reading
a+b - binary file is opened for both appending & reading.
Accessing of files:

Based on the data that is accessed, files are classified in to


a) Sequential files b) Random access file
a) Sequential files: Data is stored and retained in a sequential manner. In this
the data is keptpermanently. If we want to read the last record of file then we
need to read all the records beforethat record. It means if we want to read 10th
record then the first 9 records should be read sequentially for reaching to the
10th record
b) Random access Files: Data is stored and retrieved in a random way. In this the
data can be read and modified randomly. If we want to read the last record of the
file, we can read it directly. Ittakes less time as compared as sequential file.

STREAMS:

File streams: A stream is a series of bytes of data flow from your program to a file or vice-versa. A
stream is an abstract representation of any external source or destination for data, so the keyword,
the command line on your display and files on disk are all examples of stream. “C” provides
numbers of function for reading and writing to or from the streams on any external devices. There
are two formats of streams which are as follows:
1. Text Stream 2. Binary Stream
Text Stream:
 It consists of sequence of characters, depending on the compilers.
 Each character line in a text stream may be terminated by a newline character.
 Text streams are used for textual data, which has a consistent appearance from one
environment to another or from one machine to another.
Binary Stream:
 It is a series of bytes.
 Binary streams are primarily used for non-textual data, which is required to keep exact
contents of the file.

Standard liberary input output functions in files (or)File Operations in C


The following are the operations performed on files in c programming langauge...
 Creating (or) Opening a file
 Reading data from a file
 Writing data into a file
 Closing a file

Declaring, Opening, and Closing File Streams: you can perform four major operations on the file,
either text or binary:

1. Opening a file
2. Closing a file
3. Reading a file
4. Writing in a file
Opening a file:

To create a new file or open an existing file, we need to create a file pointer of FILE type. Following
is the sample code for creating file pointer.

File *f_ptr ;

We use the pre-defined method fopen() to create a new file or to open an existing file. There are
different modes in which a file can be opened. Consider the following code...
To create a new file or open an existing file, we need to create a file pointer ofFILE type.
Following is the sample code for creating file pointer.

File *f_ptr ;

We use the pre-defined method fopen() to create a new file or to open an existing file. There
are different modes in which a file can be opened. Considerthe following code...

File *f_ptr ;
*f_ptr = fopen("abc.txt", "w") ;

The above example code creates a new file called abc.txt if it does not existsotherwise it is
opened in writing mode.

To perform any operation (read or write), the file has to be brought into memory from the storage
device. Thus, bringing the copy of file from disk to memory is called opening the file.

The fopen() function is used to open a file and associates an I/O stream with it. The general form
of fopen() is

fopen(const char *filename, const char *mode);

or fopen ("filename","mode");

This function takes two arguments. The first argument is the name of the file to be opened while
the second argument is the mode in which the file is to be opened.

NOTE: Before opening a file, we have to create/declare a file pointer that is created using FILE
structure is defined in the “stdio.h” header file.

For example:

FILE *fp; //creating or declaring file pointer- fp

if(fp = fopen(“myfile.txt”,”r”)) == NULL)

printf(“Error opening a file”);


exit(1);

This opens a file named myfile.txt in read mode.

Fopen program:

#include<stdio.h>

void main( )

FILE *fp ;

char ch ;

fp = fopen("file_handle.c","r") ;
while ( 1 )

ch = fgetc ( fp ) ;

if ( ch == EOF )

break ;

printf("%c",ch) ;

fclose (fp ) ;

Output

The content of the file will be printed.

Closing a file:

To close a file and dis-associate it with a stream, use fclose() function. It returns zero if successful
else returns EOF if error occurs. The fcloseall() closes all the files opened previously. The general
form is:

fclose(file pointer);

Example: int main(){

FILE *fp;
fp = fopen("INPUT.txt","r") // Open file in Read mode

fclose(fp); // Close File after Reading

return(0);

Creating (or) Opening a file program :

1. Create a variable of type FILE *, and store the return value from fopen in it.
2. Check the return value to make sure it is not equal to NULL before using it. If
fopen returnsNULL, then it was unable to open the requested file for some
reason.
#include,stdio.h>

main()

FILE *fp;

fp=fopen(“data.txt”,”r”); if(fp

= = NULL)

printf(“cannot open file”);

exit(0);

Reading from a file (r)


The second parameter is the file attribute and can be any of three letters, r, w, or a, and must
be lower case. When an r is used, the file is opened for reading, a w is used to indicate a file
to be used for writing, and an a indicates that you desire to append additional data to the data
already in an existing file. Most C compilers have other file attributes available; check your
Reference Manual for details. Using the r indicates that the file is assumed to be a text file.
Opening a file for reading requires that the file already exist. If it does not exist, the file
pointer will be set to NULL and can be checked by theprogram.
Syntax:
FILE *fp
fp =fopen (“sample txt”, “r”);
a) If the file does not exists, then fopen function returns NULL value.
b) If the file exists then data is read from the file successfully
Writing to a file (w)
When a file is opened for writing, it will be created if it does not already exist and it will
be reset if itdoes, resulting in the deletion of any data already there. Using the w indicates
that the file is assumedto be a text file.
Syntax:
FILE *fp;
fp =fopen (“sample txt”, “w”);
a) If the file does not exist then a new file will be created
b) If the file exists then old content gets erased & current content will be stored.

Appending a file (a)


When a file is opened for appending, it will be created if it does not already exist and it will
be initiallyempty. If it does exist, the data input point will be positioned at the end of the
present data so that any new data will be added to any data that already exists in the file.
Using the a indicates that the file is assumed to be a text file.
Syntax:
FILE *fp;
fp =fopen (“sample txt”, “a”);
a) If the file doesn’t exists, then a new file will be created.
b) If the file exists, the current content will be appended to the old content

Closing a file
To close a file you simply use the function fclose with the file pointer in the parentheses.
Actually, inthis simple program, it is not necessary to close the file because the system will
close all open files before returning to DOS, but it is good programming practice for you to
close all files in spite of the fact that they will be closed automatically, because that would
act as a reminder to you of what files are open at the end of each program.
Syntax:
fclose(file-pointer);
Example ::

#include<stdio.h>

void main()

FILE *fptr; fptr=fopen("a.txt",“w");

if(fptr==null)

printf("\n file cannot be opened for creation");else

printf("\n file created successfully");


fclose(fptr);

Formatted file input output functions:


C fprintf() function:
To write a file in C, fprintf() function is used.Syntax:
fprintf(FILE *stream, const char *format [, argument, …])
 fprintf( *file_pointer, "text" ) - This function is used to writes/inserts multiple lines of text
with mixed data types (char, int, float, double) into specified file which is opened in writing
mode.
Example Program to illustrate "fprintf()" in C.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
char *text = "\nthis is example text";
int i = 10;
fp = fopen("MySample.txt","w");
fprintf(fp,"This is line1\nThis is line2\n%d", i);
fprintf(fp,text);
fclose(fp);
getch();
return 0;
}
Output

C fprintf() function: example 2:


To write a file in C, fprintf() function is used.Syntax:
fprintf(FILE *stream, const char *format [, argument, …])
Example of fprintf() function.
#include <stdio.h>int
main()
{
FILE *f;
f = fopen("file.txt", "w");
fprintf(f, "Reading data from a file is a common feature of file handling.\n");printf ("Data
Successfully Written to the file!");
fclose(f);
return 0;
}
Output
Data Successfully Written to the file!
Note file.txt contains Reading data from a file is a common feature of filehandling.
fscanf( *file_pointer, typeSpecifier, &variableName ) - This function is used to read multiple
datatype values from specified file which is opened in reading
mode.
Example Program to illustrate fscanf() in C.
#include<stdio.h>
#include<conio.h>
int main(){
char str1[10], str2[10], str3[10];
int year;
FILE * fp;
fp = fopen ("file.txt", "w+");
fputs("We are in 2016", fp);
rewind(fp); // moves the cursor to begining of the file
fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);
printf("Read String1 - %s\n", str1 );
printf("Read String2 - %s\n", str2 );
printf("Read String3 - %s\n", str3 );
printf("Read Integer - %d", year );
fclose(fp);
getch();

return 0;
}

Output
Character input ouput functions:
The reading from a file operation is performed using the following pre-defined file handling
methods.
Reading from a file(character input functions)
1. getc()
2. getw()
3. fgets()

Writing into a file(character output functions)


The writing into a file operation is performed using the following pre-defined file handling
methods.
1. putc()
2. putw()
3. fputs()
getc( *file_pointer ) - This function is used to read a character from specified file which is opened
in reading mode. It reads from the current position of the cursor. After reading the character the
cursor will be at next character.
Example Program to illustrate getc() in C.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
char ch;
fp = fopen("MySample.txt","r");
printf("Reading character from the file: %c\n",getc(fp));
ch = getc(fp);
printf("ch = %c", ch);
fclose(fp);
getch();
return 0;
}
Output

 getw( *file_pointer ) - This function is used to read an integer value form the specified file
which is opened in reading mode. If the data in file is set of characters then it reads ASCII
values of those characters.
Example Program to illustrate getw() in C.
#include<stdio.h>
int main(){
FILE *fp;
int i,j;
fp = fopen("MySample.txt","w");
putw(65,fp); // inserts A
putw(97,fp); // inserts a
fclose(fp);
fp = fopen("MySample.txt","r");
i = getw(fp); // reads 65 - ASCII value of A
j = getw(fp); // reads 97 - ASCII value of a
printf("SUM of the integer values stored in file = %d", i+j); // 65 + 97 = 162
fclose(fp);
getch();
return 0;
}
Output

fgets( variableName, numberOfCharacters, *file_pointer ) - This method is used for reading a set
of characters from a file which is opened in reading mode starting from the current cursor
position. The fgets() function reading terminates with reading NULL character.

Example Program to illustrate fgets() in C.

#include<stdio.h>

#include<conio.h>

int main(){

FILE *fp;

char *str;
clrscr();
fp = fopen ("file.txt", "r");
fgets(str,6,fp);
printf("str = %s", str);
fclose(fp);
getch();
return 0;
}

Output:
putc( char, *file_pointer ) - This function is used to write/insert a character to the specified
file when the file is opened in writing mode.
Example Program to illustrate putc() in C.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
char ch;
fp=fopen("C:/TC/EXAMPLES/MySample.txt","w");
putc('A',fp);
ch = 'B';
putc(ch,fp);
fclose(fp);

getch();

return 0;

} Output

 putw( int, *file_pointer ) - This function is used to writes/inserts an integer value to the
specified file when the file is opened in writing mode.
Example Program to illustrate putw() in C.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
int i;
fp = fopen("MySample.txt","w");
putw(66,fp);
i = 100;
putw(i,fp);
fclose(fp);
getch();
return 0;
} Output
 fputs( "string", *file_pointer ) - TThis method is used to insert string data into specified file
which is opened in writing mode.
Example Program to illustrate fputs() in C.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
char *text = "\nthis is example text";
clrscr();
fp = fopen("MySample.txt","w");
fputs("Hi!\nHow are you?",fp);
fclose(fp);
getch();
return 0;
}
Output

Cursor Positioning Functions in Files


C programming language provides various pre-defined methods to set the cursor position in files.
The following are the methods available in c, to position cursor in a file.
1. ftell()
2. rewind()
3. fseek()

 ftell( *file_pointer ) - This function returns the current position of the cursor in the file.
Example Program to illustrate ftell() in C.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
int position;
fp = fopen ("file.txt", "r");
position = ftell(fp);
printf("Cursor position = %d\n",position);
fseek(fp,5,0);
position = ftell(fp);
printf("Cursor position = %d", position);
fclose(fp);
getch();
return 0;
}
Output

 rewind( *file_pointer ) - This function is used reset the cursor position to the beginning of
the file.
Example Program to illustrate rewind() in C.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
int position;
clrscr();
fp = fopen ("file.txt", "r");
position = ftell(fp);
printf("Cursor position = %d\n",position);
fseek(fp,5,0);
position = ftell(fp);
printf("Cursor position = %d\n", position);
rewind(fp);
position = ftell(fp);
printf("Cursor position = %d", position);
fclose(fp);
getch();
return 0;
}
Output
 fseek( *file_pointer, numberOfCharacters, fromPosition ) - This function is used to set the
cursor position to the specific position. Using this function we can set the cursor position
from three different position they are as follows.
o from beginning of the file (indicated with 0)
o from current cursor position (indicated with 1)
o from ending of the file (indicated with 2)

Example Program to illustrate fseek() in C.


#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
int position;
clrscr();
fp = fopen ("file.txt", "r");
position = ftell(fp);
printf("Cursor position = %d\n",position);
fseek(fp,5,0);
position = ftell(fp);
printf("Cursor position = %d\n", position);
fseek(fp, -5, 2);
position = ftell(fp);
printf("Cursor position = %d", position);
fclose(fp);
getch();
return 0;
}
Output
Example Program to illustrate fgets() in C.#include<stdio.h>
#include<conio.h> int
main(){
FILE *fp;
char *str;
clrscr();
fp = fopen ("file.txt", "r");
fread(str,sizeof(char),5,fp);
str[strlen(str)+1] = 0; printf("str =
%s", str); fclose(fp);
getch();

return 0;
}
Output

 numberOfCharacters, FILE *pointer ) - This function is used to insert specified number of


characters into a binary file which is opened in writing mode.
Example Program to illustrate fwrite() in C.
#include<stdio.h>
#include<conio.h>
int main(){
FILE *fp;
char *text = "Welcome to C Language";
clrscr();
fp = fopen("MySample.txt","wb");
fwrite(text,sizeof(char),5,fp);
fclose(fp);
getch();
return 0;
}
Output
Standard liberary functions on files:

1. stdin - Standard input, normally the keyboard.


2. stdout - Standard output, normally the screen. ( Although it is somewhat
common to redirectstdout to a file for later use. )
3. stderr - Standard error, also normally the screen. The benefit of having both
stdout and stderris that if the "results" of the program written to stdout are
redirected to a file, then the messages written to stderr are still sent to the
screen.

File conversions

1. text file to binary file


Binary file to text file
Example :

C program to convert text file to binary

#include <stdio.h>
#include <string.h>
#define MAX 256

int main() {
int num;
FILE *fp1, *fp2;
char ch, src[MAX], tgt[MAX];

/* get the input file name from the user */


printf("Enter your input file name:");
scanf("%s", src);

/* get the output filename from the user */


printf("Enter your output file name:");
scanf("%s", tgt);
/* open the source file in read
mode */fp1 = fopen(src, "r");
/* error
handling */if
(!fp1) {
printf("Unable to open the input
file!!\n");return 0;
}
/* open the target file in binary write
mode */fp2 = fopen(tgt, "wb");

/* error
handling */if
(!fp2) {
printf("Unable to open the output
file!!\n");return 0;
}
/*
* read data from input file and write
* the binary form of it in output file
*/
while (!feof(fp1)) {
/* reading one byte of
data */ fread(&ch,
sizeof(char), 1, fp1);
/* converting the character to ascii integer
value */num = ch;
/* writing 4 byte of data to the
output file */fwrite(&num, sizeof(int),
1, fp2);
}
/* close all opened
files */fclose(fp1);
fclos
e(fp
2);
retu
rn 0;
}
Output: jp@jp-VirtualBox:~/$ cat data.txt
abcde
fg123
4
56789
hijklm
12345
6abcd
e
fghijk1
2345
jp@jp-VirtualBox:~/$ ./a.out
Enter your input file name:
data.txt Enter your output
file name: res.bin

a^@^@^@b^@^@^@c^@^@^@d^@^@^
@e^@^
a^@^@^@b^@^@^@c^@^@^@d^@^@^
@e^@^
a^@^@^@b^@^@^@c^@^@^@d^@^@^
@e^@^

output 2: Enter your input file

name:srcEnter your output file

name:tgt

Unable to open the input file!!

You might also like