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

Functions

c programming

Uploaded by

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

Functions

c programming

Uploaded by

Haf hafeefa
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 48

Modular Programming

-Functions in C
Functions
Introduction to modular programming, writing
functions, formal parameters, actual parameters.
Pass by Value, Recursion, Arrays as Function
Parameters.

structure, union.
Storage Classes, Scope and life time of
variables simple programs using functions.

2
Modular Programming

Dividing a large problem into sub-problems and developing
subprogram for each of the sub-problems.

If the sub-problems itself is large enough, then it can further
divided into smaller problems.

Advantages :-

Modules can be written and tested separately.

Modules can be reused.

Reduces the length of the program making it more readable.

Program maintenance is easier.

Several programmers can work on the same
program ,each programmer is working on
separate modules.
Modular Programming

Advantages :-

Many programs require that a particular group of instructions
be accessed repeatedly, from several different places within
the program.

The repeated instructions can be placed within a single
function, which can then be accessed whenever it is needed.

Moreover, a different set of data can be transferred to the
function each time it is accessed.

Thus, the use of a function avoids the need for redundant
(repeated) programming of the same instructions.

4
Modular Programming

Different languages uses different terms for
representing the subprograms.

Subroutines

Procedures

Functions

In C language only one kind of subprograms, namely
functions.

Decomposition of a program into individual program
modules is generally considered to be an important part
of good programming practice.

5
Functions in C
Modular
Programming :
Types of functions

There are two types of function in C programming:


•Standard library functions

•User-defined functions
Standard Library function
•The standard library functions are built-in functions in C
programming.

•These functions are defined in header files. For example,


•The printf() is a standard library function to send formatted output to the
screen (display output on the screen). This function is defined in the stdio.h
header file.

•Hence, to use the printf()function, we need to include the stdio.h header file
using #include <stdio.h>.

•The sqrt() function calculates the square root of a number. The function is
defined in the math.h header file.
User-defined functions

•User can also create functions as


per user’s need.

•Such functions created by the


user are known as user-defined
functions.
//Simple Program using Function
#include<stdio.h>
int addNumbers(int a,int b); // Function prototype
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
Functions in C

A function is a self-contained program segment that carries
out some specific, well-defined task.

Every C program consists of one or more functions.

One of these functions must be called main.

Execution of the program will always begin by
carrying out the instructions in main.

Additional functions will be subordinate to main, and
perhaps to one another.

Normally we will write the main function first followed by
other function definitions.
Functions in C

If a program contains multiple functions, their definitions may
appear in any order.

A function is independent of another function.

One function definition cannot be embedded within another.

A function will carry out its intended action whenever it is
accessed (i.e., whenever the function is "called") from some
other portion of the program.

The same function can be accessed from several different
places within a program.

Once the function has carried out its intended action,
control will be returned to the point from which the
function was accessed.
Functions in C

Generally, a function will process information that is passed
to it from the calling portion of the program, and return a
single value.

Information is passed to the function via special identifiers
called
arguments (also called parameters).

Result is returned via the return statement.

Some functions, however, accept information but do
not return anything.

The function which does not return any value is called
void function.
Defining a Function

A function definition has two parts :

function header and

body of the function.

Function header contains :

the type of value returned by the function,

followed by the function name (an identifier), and

(optionally) a set of arguments, separated by
commas and enclosed in parentheses.

Each argument is preceded by its associated type
declaration.

An empty pair of parentheses must follow the function
name if the function definition does not include any
arguments.
Defining a Function
General form of a Function Formal
parameters
Definition:
data_type fname(type1 arg1, type2 arg2, ..., typen
argn)
{ local variable No
declaration semicolon
............
group of
statements
.........
return // optional
} expression;
Accessing a Function

A function can be accessed (i.e., called) by specifying its name,
followed by a list of arguments enclosed in parentheses and
separated by commas.

If the function call does not require any arguments, an
empty pair of parentheses must follow the name of the
function.

The function call may be a part of a simple expression (such
as an assignment statement), or it may be one of the
operands within a more complex expression.

General form of accessing a Function:

fname(arg1, arg2, ...... , argn);


actual arguments
Function Declaration ( Prototype)

Function declaration is required

when the function is called before its definition and

if the type of value returned by the function is other than
int or char.


General form of function declaration is:

data_type fname(type1 arg1, type2 arg2, ......typen argn);

Function declaration in ANSI format (as given above) is called
function prototype


It can also be written as

data_type fname(type1, type2, ......, typen);

Function Example 1
// function for finding the sum of two integer numbers.
#include
<stdio.h> void
main()
{
int a, b,
s;
printf(“Enter Two Numbers
: “); scanf(“%d%d”,
&a,&b);
s = sum(a,b); // a, b – actual
int sum(int x,
parameters // x, y – formal
printf(“Sum = %d\n”, s);
int
} y) parameters
{
return x+y;
}
Function Example 2
// function for finding the largest of three integer numbers.
#include
<stdio.h> void
main()
{
int a, b,
c;
printf(“Enter Three Integers : “);
scanf(“%d%d%d”, &a, &b, &c);
printf(“Largest = %d\n”,
int largest(int a, int b,
largest(a,b,c)); // formal parameters can have any
int
{
} c)int lar; name
lar = a>b? a>c?a:c :
b>c?b:c; return lar;
}
Function Example 3
// function for converting a charater to upper
case.
#include
<stdio.h> void
main()
{ char str[50]; int i;
printf(“Enter a string
: “); scanf(“ %[^\
n]”, str);
for (i=0; str[i] != ‘\0’ ;
i++) str[i] =
char uppercase(char ch)
uppercase(str[i]); // ‘a’ - ‘A’
{ printf(“Upper case string : is
return
%s\n”,ch>=’a’
str); 32
&& ch <=’z’ ?
} ch-32 : ch;
}
Function Example 4
// function for finding the average of two integers.
#include <stdio.h>
float average(int, int); // function
declaration. void main()
{ int a, b; float avg;
printf(“Enter two
integers : “); scanf(“%d
%d”, &a, &b);
avg = average(a,b);
printf(“Average = %f\n”,
avg);
}

float average(int a, int b)


{
return (a+b)/2.0;
}
Exercise
Write a menu driven program in which we can do the following
functionalities.
1. Read a number.
2. Find the factorial of a number.
3. Find the sum of the digits of a number.
4. Check if the number is prime or not.
5. Exit.
Passing arguments to a function
•In programming, argument refers
to the variable passed to the
function. In the example, two
variables n1 and n2 are passed
during the function call.

•The parameters a and b accepts


the passed arguments in the
function definition. These
Return Statement
• The return statement terminates the execution
of a function and returns a value to the calling
function. The program control is transferred to
the calling function after the return statement.

• In the example, the value of the result variable


is returned to the main function. The sum
variable in the main() function is assigned this
value.
Recursio
n
Recursion

Recursion is a process by which a function calls itself repeatedly,
until some specified condition has been satisfied.

The process is used for repetitive computations in which each action
is stated in terms of a previous result.

Many iterative (i.e., repetitive) problems can be written using
recursion.

Since lot of function calls are involved it will take more time
and memory compared to iteration.

Multiple instances of same function may exist on the stack at
the same time.

In order to solve a problem recursively, two conditions must be
satisfied.

First, the problem must be written in a recursive form

Second, the problem statement must include a stopping
Recursion

If a recursive function contains local variables, a different set of
local variables will be created during each call.

The names of the local variables will be the same, as declared
within the function.

However, the variables will represent a different set of values
each time the function is executed.

Each set of values will be stored on the stack, so that they will be
available as the recursive process “unwinds,” i.e., as the various
function calls are “popped” off the stack and executed.
Recursion

Consider the case of finding factorial of a
number (N!)

It is defined as

N! = 1x2x3x...............x N

It can be defined recursively as

N! = N (N-1)!

Terminating case is 0! =1 , 1! = 1

4! = 4 x 3!
=4x3x 2!
=4x3x 2 x 1!
=4x3x 2x1
=4x3x 2
=4x6
= 24
Recursion- Example 1
//Recursive function for
finding n! long int
factorial(int);
void main()
{ int n; long fact; factorial(3)
3*factorial(2)
printf(“Enter n :
“);
3*2*factorial
scanf(“%d”,&n
(1) 3*2*1
); fact =
} factorial(n);
longprintf(“%d ! = k)
int factorial(int
{ %ld\n”,n,fact);
if (k)
return k*factorial(k-1);
else
return 1;
}
Recursion- Example 2

//Recursive function for finding kth Fibonacci


number
// Fibonacci series 0 1 1 2 3 5 8
13 ............. int fib(int);
{
void main() int fib(int k)
int n,i; {
printf(“How many terms int
: “); scanf(“%d”,&n); f1,f2;
printf(“\nFirst %d Fibonacci Numbers :\ if
n”,n); for (i=1; i<=n; i++) (k<=1)
printf(“%4d”,fib(i)); return Recursio
} k; f1 n
=fib(k-1);
f2
=fib(k-2);
return
f1+f2;
Recursion- Questions

Factorial of n

Kth fibonacci number

Sum of digits of a counting
number

Decimal to binary conversion

GCD of two numbers

Largest of N numbers

Binary Search

Find permutations of a word
•Example: Sum of Natural Numbers Using Recursion
#include <stdio.h>
int sum(int n);
int main() {
int number,
result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum = %d", result);
return 0;
}
int sum(int n) {
Passing Arrays to
● Function
An array can be passed to a function as an argument.

The manner in which the array is passed differs from that of an
ordinary variable.

To pass an array to a function, the array name must appear by
itself, without brackets or subscripts, as an actual argument
within the function call.

When declaring a one-dimensional array as a formal argument, the
array name is written with a pair of empty square brackets.

The size of the array is not specified within the formal argument
declaration.
Passing Arrays to
● Function
Writing function prototypes that include array arguments.

An empty pair of square brackets must follow the name of each array
argument, thus indicating that the argument is an array.

If argument names are not included in a function declaration, then an
empty pair of square brackets must follow the array argument data
type.
Passing Arrays to
● Function
In C, arguments are passed to a function by value when the
arguments are ordinary variables.

When an array is passed to a function, however, the values of the array
elements are not passed to the function.

Rather, the array name is interpreted as the address of the first
array element (i.e., the address of the memory location containing
the first array element).

This address is assigned to the corresponding formal argument
when the function is called.

The formal argument therefore becomes a pointer to the first
array element.

Arguments that are passed in this manner are said to be passed
by reference
rather than by value.
Passing Arrays to

When a reference is Function
made to an array element within the function,
the value of the element's subscript is added to the value of the
pointer to indicate the address of the specified array element.

Therefore any array element can be accessed from within the
function.

Moreover, if an array element is altered within the function, the
alteration will be recognized in the calling portion of the program.
Array as Parameter
// Function for finding sum of elements int sum_array(int b[ ],
in an array. int n)
void read_array(int a[ ], {
int n); int int s=0, i;
sum_array(int a[ ], int n); for (i=0; i<n:
void main() i++) s =
{ s+b[i];
int a[10], n; return s;
printf(“Howmany }
Nos ? ”); scanf(“%d”,
&n); read_array(a, n);
printf(“Sum = %d\n”,
sum_array(a,n));
}

int read_array(int a[ ], int


n)
{ int i;
for (i=0; i<n; i++)
Array as Parameter

int string_length(char
s[ ]); void main()
{
char str[80];
int len; printf(“Enter
a String : ”);
scanf(“ %[^\n]”, str);
len = string_length(str);
printf(“Length of string = %d\
n”, len);
}

int string_length(char s[ ])
{ int i;
for (i=0; s[i] != ‘\0’;
i++); return i;
}
Array as Parameter
// Function for reversing a string.
void string_reverse(char
void string_reverse(char s[ ])
s[ ]); void main() {
{ int L=0, R; char
char str[80]; int ch;
len; printf(“Enter a for (R=0; s[R]!=’\0’;
String : ”); R++)
scanf(“ %[^\n]”, str); ;
string_reverse(str); R--; // points to
printf(“Reversed last char while (L<R)
string : %s\n”, str); { ch =s[L];
} s[L]=s[R];
} s[R]=ch;
return
} ; L++; R--;
Passing 2D Array to
● Function
In case of a multi-dimensional array, the formal argument
declarations within the function definition must include explicit
size specifications in all of the subscript positions except the
first.

In case of 2D array (formal parameter) we have to specify the
number of columns.

These size specifications must be consistent with the
corresponding size specifications of the actual arguments.

The first subscript position may be written as an empty pair
of square brackets, as with a one-dimensional array.

The corresponding function prototypes must be written in
the same manner.
Passing 2D Array to
Function void read_mat(int a[ ][10], int m,
// Sum of two matrices int n)
{ int i,j;
void read_mat(int a[ ][10], int m, int n); printf(“Enter matrix of
void sum_mat(int a[ ][10], int b[ ][10], int order”); printf (“ %d x
m, int n); %d\n”, m,n);
void display_mat(int a[ ][10], int m, int n); for (i=0; i<m; i++)
for (j=0; j<n; j++)
void main() } scanf(“%d”, &a[i]
{ int a[10][10], b[10][10], c[10][10]; [j]);
int m, n; void
returnsum_mat(int
; a[ ][10], int
b[ ][10],
int c[ ][10], int m, int n)
printf(“Enter order of Matrix : ”); { int i,j;
scanf(“%d%d”, &m, &n); for (i=0; i<m; i++)
read_mat(a,m,n); for (j=0; j<n; j++)
read_mat(b,m,n); c[i][j]=a[i][j] +
sum_mat(a,b,c,m,n); b[i][j];
printf(“Sum is :\n”); }
display_mat(c,m,n); void display_mat(int a[ ][10], int
} m, int n)
{ ........
Passing Individual Array Elements
•Passing array elements to a function is similar to passing variables to a function.
Passing Arrays to Functions
Pass Multidimensional Arrays to a Function
Parameter Passing

In general mainly two kinds of parameter passing

Passing by value

Passing by reference

Passing by value :

Value of actual parameter is copied to formal parameter.

Any changes made to formal parameter does not affect the
value of actual parameter.

C language supports this kind of parameter passing.

Passing by referrence:

Address of actual parameter is copied to formal parameter.

Any changes made to formal parameter affect the value
of actual parameter.
Pass by value
•The value of the actual parameters is copied into the formal
parameters.

•We can not modify the value of the actual parameter by the formal
parameter.

•Different memory is allocated for actual and formal parameters since


the value of the actual parameter is copied into the formal
parameter.

•The actual parameter is the argument which is used in the function


•Example to understand the concept of pass by value in c language.

void
modify(int);
void main()
{ Outpu
int a=10; t:
a=10
printf(“a=%d\ After function
n”,a); call. a=10
modify(a);
printf(“After
void
function
modify(int
call.\n
k) a=%d”,a);
}
{
k=200;
}
Excercise on 1D and 2D Array passing

Function for finding/doing

Smallest element in an array.

Average of numbers in an array.

Linear Search.

Coverting all letters of a string to uppercase.

Concatinating one string to another.

Matrix multiplication.

Checking whether a square matrix is symmetric.

Finding largest element in a matrix.

Finding sum of major diagonal elements of a square
matrix.

String sorting

You might also like