4 Function
4 Function
P r o g r a m m i n g - f u n c ti o n s
M o d u l a r p r o g r a m m i n g a n d
F u n c ti o n s
1
Modularization and Function
• Process of splitting the lengthier and complex programs
into a number of smaller units is called Modularization.
2
Functions
Standard functions
(library functions or built in functions)
User-defined functions
Written by the user(programmer)
3
General form of function definition
return_type function_name(parameter_definition)
{
variable declaration;
statement1;
statement2;
.
.
.
return(value_computed);
}
4
Defining a Function
Name (function name)
• You should give functions descriptive names
• Same rules as variable names, generally
Return type
• Data type of the value returned to the part of the program that activated (called)
the function.
Parameter list (parameter_definition)
• A list of variables that hold the values being passed to the function
Body
• Statements enclosed in curly braces that perform the function’s operations(tasks)
5
Understanding of main function
}
{
printf(“hello world\n”); Body
return 0;
}
6
Function Definition and Call
// FUNCTION DEFINITION
Return typeFunction Parameter
name
void DisplayMessage(void) List
{
printf(“Hello from function DisplayMessage\n”);
}
int main()
{
printf(“Hello from main \n”);
DisplayMessage(); // FUNCTION CALL
printf(“Back in function main again.\n”);
return 0;
}
7
Multiple Functions- An example
void First (void){ // FUNCTION DEFINITION
printf(“I am now inside function First\n”);
}
void Second (void){ // FUNCTION DEFINITION
printf( “I am now inside function Second\n”);
First(); // FUNCTION CALL
printf(“Back to Second\n”);
}
int main (){
printf( “I am starting in function main\n”);
First ();
printf( “Back//toFUNCTION CALL
main function \n”);
Second ();
printf( “Back //toFUNCTION CALL
main function \n”);
return 0;
}
8
Arguments and parameters
Variables used in the function reference or function
call are called as arguments.
These are written within the parenthesis followed by
the name of the function. They are also called actual
parameters (during call).
Variables used in function definition are called
parameters, They are also referred to as formal
parameters.
9
Functions
Formal
parameters
11
Local Variables
• Variables that are declared inside a function are called
local variables.
• They can be used only by statements that are inside that
function.
• In the following example all the variables a, b, and c are
local to main() function.
#include <stdio.h>
int main () {
/* local variable declaration */
int a, b, c;
a = 10; b = 20; c = a + b;
printf ("value of a = %d, b = %d and c =
%d\n", a, b, c);
return 0;
12
}
Global Variables
• Global variables are defined outside a function, usually
on top of the program.
• Global variables hold their values throughout the lifetime
of your program and they can be accessed inside any of
the functions defined for the program.
#include <stdio.h>
int g; /* global variable declaration */
int main () {
int a, b; /* local variable declaration */
a = 10; b = 20; g = a + b;
printf ("value of a = %d, b = %d and g =
%d\n", a, b, g);
return 0;
13
}
Functions- points to note
1. The parameter list must be separated by commas.
dispChar( int n, char c);
2. The parameter names do not need to be the same in the prototype
declaration and the function definition.
3. The types must match the types of parameters in the function
definition, in number and order.
void dispChar(int n, char c); //proto-type
void dispChar(int num, char ch){
printf(" You have entered %d &%c”,
num,ch);
}
4. Use of parameter names in the declaration(prototype) is optional
but parameter type is a must.
void dispChar(int , char); //proto-type
14
Functions- points to note
5. If the function has no formal parameters, the list can be
written as (void) or simply ()
6. The return type is optional, when the function returns
integer type data.
7. The return type must be void if no value is returned.
8. When the declared types do not match with the types
in the function definition, compiler will produce error.
15
Functions- Categories
Categorization based on the arguments and return
values
1. Functions with no arguments and no return
values.
2. Functions with arguments and no return
values.
3. Functions with arguments and one return
value.
4. Functions with no arguments but return a
value. 16
Function with No Arguments/parameters & No return
values
dispPattern(); // prototype
int main(){
printf(“fn to display a line of stars\n”);
dispPattern();
return 0;
}
dispPattern(){
int i;
for (i=1;i<=20 ; i++)
printf( “*”);
}
17
Function with No Arguments but A return value
int readNum(void); // prototype
int main(){
int c;
printf(“Enter a number \n”);
c=readNum();
printf(“The number read is %d“,c);
return 0;
}
int readNum(){
int z;
scanf(“%d”,&z);
return(z);
}
18
Fn with Arguments/parameters & No return values
void dispPattern(char ch); // prototype
int main(){
printf(“fn to display a line of patterns\n”);
dispPattern(‘#’);
dispPattern(‘*’);
dispPattern(‘@’);
return 0;
}
void dispPattern(char ch ){
int i;
for (i=1;i<=20 ; i++)
printf(“%c”,ch);
}
19
Function with Arguments/parameters & One return
value
int fnAdd(int,int);
int main(){
int a,b,c;
printf(“\nEnter numbers to be added\n”);
scanf(“%d %d”,&a,&b);
c=fnAdd(a,b);
printf(“Sum is %d “, c);
return 0;
}
int fnAdd(int x, int y ){
int z;
z=x+y
return(z);
} 20
Extra Problems…
Write appropriate functions to
1. Find the factorial of a number ‘n’.
2. Reverse a number ‘n’.
3. Check whether the number ‘n’ is a palindrome.
4. Generate the Fibonacci series for given limit ‘n’.
5. Check whether the number ‘n’ is prime.
6. Generate the prime series using the function written
for prime check, for a given limit.
21
Parameter passing techniques
22
Functions- Parameter Passing
2
3
Pass by value:
void swap(int x, int y )
{
int t=x;
x=y;
y=t;
printf(“In fn: x= %d and y=%d “,x,y);
}
Output:
int main() In fn: x = 7 & y = 5
{ After swap: a = 5 & b = 7
int a=5,b=7;
swap(a, b);
printf(“After swap: a= %d and b= %d“,a,b);
return 0;
2
} 4
Pass by Reference – Using Pointers:
void swap(int *x, int *y )
{ Change is directly on the
int t=*x; variable using the reference
*x=*y; to the address.
*y=t; When function is
called:
}
address of a x
address of b y
Output:
int main() After swap: a = 7
{ and b = 5
int a=5,b=7;
swap(&a, &b);
printf(“After swap: a=%d and b= %d”,a,b);
return 0; } 2
5
Pointers as functions arguments:
When we pass addresses to a function, the parameters receiving
the addresses should be pointers.
int change (int *p) #include <stdio.h>
{ int main()
*p = *p + 10 ; {
return 0; int x = 20;
} change(&x); Output :
X after change=30
printf(“x after change==
%d“,x);
return 0;
}
26
Pointers as function arguments
• When the function change() is called, the address of the
variable x, not its value, is passed into the function
change().
32
Passing 1D-Array to Function:
int fnSum( int a[ ], int n) {
int sum=0,i;
for(i=0;i<n;i++)
sum+=a[i];
return (sum); } Output: n=5
1, 2, 3, 4, 5
int main() { Sum of
int n, a[20], x, y,i; elements = 15
printf(“Enter the limit \n“); Array name is passed
scanf(“%d”,&n); along with number of
printf(“Enter the values: \n“); elements
for (i=0; i<n; i++)
scanf(“%d”,&a[i]);
printf(“The sum of array elements is =%d “,fnSum(a, n));//fn call
return 0; }
33
Passing 2D-Array to Function:
34
Passing 2D-Array to Function:
int fn2d(int x[ ][10], int m, int n)
{
int i, j, sum=0; Output: m=2 n=3
for(i=0; i<m; i++) 1 2
for(j=0; j<n; j++) 3 4
sum+=x[i][j]; 5 6
return(sum); Sum of elements = 21
}
int main() {
int i, j, a[10][10], m, n;
printf("Enter dimentions of matrix");
scanf("%d%d", &m, &n);
printf("Enter the elements");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf ("Sum of elements of 2D array is=%d",fn2d(a, m, n));
return 0;
}
35
Extra problems:
• Write a c program to add all the even elements of an array
using a function Add().
36
Write a c program to add all the even elements of an array using a function Add()
37
Write a C program to replace all odd numbers of an array with the largest number in the array using a function Replace()
#include <stdio.h>
void Replace( int arr[ ], int main()
int n) {
{ int n, a[20], x, y,i;
// To find the largest printf("Enter the limit \n");
int i, max = arr[0]; scanf("%d",&n);
for (i = 1; i < n; i++) printf("Enter the values: \n");
if (arr[i] > max) for (i=0; i<n; i++)
max = arr[i]; scanf("%d",&a[i]);
Replace(a,n);
// To replace printf("The array after replacement is\n");
for(i=0;i<n;i++) for (i=0; i<n; i++)
{ printf("%d \n",a[i]);
if(arr[i]%2 != 0)
arr[i]=max; return 0;
} }
}
38
Write a C program to replace all the zeros in the matrix by the trace of the matrix using a function Trace()
int main() {
#include <stdio.h> int i, j, m, n;
#include <math.h>
float a[10][10];
void Trace(float a[ ][10], int m, int n)
printf("Enter dimentions of matrix");
{ scanf("%d %d", &m, &n);
int i, j, norm, sum=0; printf("Enter the elements");
for(i=0;i<m;i++)
// Finding Trace for(j=0;j<n;j++)
for(i=0;i<m;i++) scanf("%f",&a[i][j]);
{ Trace(a, m, n);
for(j=0;j<n;j++) printf("Matrix after replacement \n");
sum=sum+a[ i ][ j]*a[ i ][ j ]; for(i=0;i<m;i++)
} {
norm=sqrt(sum); for(j=0;j<n;j++)
//Replacing zeros {
for(i=0;i<m;i++) printf("%f",a[i][j]);
for(j=0;j<n;j++) }
if(a[i][j]==0) printf("\n");
a[i][j]=sum; }
return 0;
} 39
}
Write a C program using pass-by-pointer method to compute the simple interest and compound interest using a function SI_CI()
#include <stdio.h>
#include <math.h>
int main() {
float p,q,r,SI,CI;
int n;
printf("Enter the value of Principal p = ");
scanf("%f",&p);
printf("Enter the value of Rate r = ");
scanf("%f",&r);
printf("Enter the value of Period in year n = ");
scanf("%d",&n);
SI_CI(&p,&r,&n,&SI,&CI);
return 0;
} 40
Write a C program using pass-by-pointer method to compute the simple interest and compound interest using a function SI_CI()
void SI_CI(float *pr, float *ra, int *yr, float *smp, float
*cmp)
{
int amount;
// Simple interest
*smp = ((*pr)*(*ra)*(*yr)/100);
// Compound interest
amount= (*pr)*pow((1 +(*ra)/100),(*yr));
*cmp= amount-(*pr);
}
41
RECURSION
What is Recursion ?
• Sometimes, the best way to solve a problem is by solving a
smaller version of the exact same problem first.
43
Let us consider the code …
int main() {
int i, n, sum=0;
printf("Enter the limit“);
scanf(“%d”,n);
printf("The sum is %d“,fnSum(n));
return 0;
}
int fnSum(int n){
int sum=0;
for(i=1;i<=n;i++)
sum=sum+i;
return (sum);
} 44
Steps to Design a Recursive Algorithm
Base case:
It prevents the recursive algorithm from running forever.
Recursive steps:
Identify the base case for the algorithm.
Call the same function recursively with the parameter
having slightly modified value during each call.
This makes the algorithm move towards the base case and
finally stop the recursion.
45
Let us consider same code again …
int main() {
int i, n, sum=0; int fnSum(int x) {
printf("Enter the limit“); if (x == 1) //base case
scanf(“%d”, n);
return 1;
printf(“The sum is %d“,fnSum(n));
return 0; else
} return x + fnSum(x-1) ;
So factorial(5)
= 5* factorial(4)
= 4* factorial(3)
= 3*factorial(2)
= 2* factorial(1)
=
1*factorial(0)
47
Factorial- recursive procedure
#include <stdio.h>
long factorial (long a) {
if (a ==0) //base case
return (1);
return (a * factorial (a-1));
}
int main () {
long number;
printf("Please type a number: “);
scanf(“%d”, number);
printf(“number ! = %d”, factorial (number));
return 0;
}
48
Recursion - How is it doing!
rFact(5) 120
x =2 = 120
5 rFact(4)
4
Notice that the
recursion isn’t x
finished at the 4 rFact(3) = = 24
6
bottom --
It must unwind all x =
3 rFact(2) = 6
the way back to the
2
top in order to be
factorial(0) = 1
done.
factorial(n) = n * 2
x
rFact(1) = = 2
factorial(n-1) [for n>0] 1
So fibonacci(4)
= fibonacci(3) + fibonacci(2)
= (fibonacci(2) + fibonacci(1)) + (fibonacci(1) + fibonacci(0))
= ((fibonacci(1) + fibonacci(0)) + 1) + (1 + 0)
= ( 1 + 0 ) + 1) + (1 + 0)
=3
50
Fibonacci Numbers: Recursion
Fibonacci series is 0,1, 1, 2, 3, 5, 8 …
int rfibo(int n)
{
if (n <= 1)
return n;
else
return (rfibo(n-1) + rfibo(n-2));
}
Output:
n=4
fib = 3
51
Recursive Calls initiated by Fib(4)
52
Fibonacci Series using Recursion
int rfibo(int);
int main(void){
int n,i, a[20], fibo;
printf("enter any num to n\n“);
scanf(“%d”, n);
printf(“Fibonacci series “);
for (i=1; i<=n; i++)
{
fibo = rfibo(i);
printf(“%d”, fibo);
}
return 0;
}
53
GCD: Recursion
Output:
x= 24 , y = 9
gcd = 3
54
Recursion - Should I or Shouldn’t I?
• Pros • Cons
– Recursion is a – Recursive programs
natural fit for typically use a large
recursive problems amount of computer
memory and the greater
the recursion, the more
memory used
– Recursive programs can
be confusing to develop
and extremely
complicated to debug
55
Recursion vs Iteration
RECURSION ITERATION
56
Recursion – Do’s
• You must include a termination condition or Base
Condition in recursive function; Otherwise your
recursive function will run “forever” or infinite.
• Each successive call to the recursive function must be
nearer to the base condition.
57
Extra Problem- Finding product of two numbers
#include <stdio.h> int product(int a, int b)
{
int product(int, int); if (a < b)
int main() {
return product(b, a);
{
}
int a, b, result; else if (b != 0)
printf("Enter two numbers to find their product: "); {
return (a + product(a, b - 1));
scanf("%d%d", &a, &b); }
result = product(a, b); else
{
printf("%d * %d = %d\n", a, b, result); return 0;
return 0; }
}
}
Output:
Enter two numbers to find their product: 10
20
10*20=200
58
Extra Problem- Dividing two numbers
#include <stdio.h> int divide(int a, int b)
int divide(int a, int b); {
if(a - b <= 0)
{
int main() return 1;
{ }
else
int a,b; {
return divide(a - b, b) + 1;
printf("Enter two numbers for division"); }
}
scanf("%d%d", &a,&b);
printf("%d/%d=%d",a,b,divide(a,b));
return 0;
} Output:
Enter two numbers for division: 20 10
20/10=2
59
Extra Problem- Calculating power of a number
#include <stdio.h> int power(int base, int powerRaised)
int power(int n1, int n2); {
if (powerRaised != 0)
return (base*power(base, powerRaised-1));
int main()
else
{ return 1;
int base, powerRaised, result; }
return 0;
}
60
Extra Problem- Sum of natural numbers
#include <stdio.h> int sum(int num)
int sum(int n); {
if (num!=0)
return num + sum(num-1);
int main()
else
{ return num;
int number, result; }
printf("sum=%d", result);
}
61
Extra Problem- To count number of digits
#include <stdio.h>
int countDigits(int num)
int countDigits(int);
{
int main() static int count=0;
{
int number; if(num>0)
int count=0; {
count++;
printf("Enter a positive integer number: "); countDigits(num/10);
}
scanf("%d",&number);
else
{
count=countDigits(number); return count;
}
printf(“Number of digits is: %d\n",count); }
Output:
return 0; Enter a positive integer number: 123
Number of digits is: 3
}
62
Extra Problem- To find sum of all digits
#include <stdio.h>
int sumDigits(int num)
int sumDigits(int num); {
int main() static int sum=0;
{ if(num>0)
int number,sum; {
sum+=(num%10);
sumDigits(num/10);
printf("Enter a positive integer number: ");
}
scanf("%d",&number); else
{
sum=sumDigits(number); return sum;
}
printf("Sum of all digits are: %d\n",sum); }
Output:
return 0; Enter a positive integer number: 123
} Number of digits is: 3
63
Extra Problem-Reversing a Number
64
Extra Problem- To find length of a string
#include <stdio.h>
int length(char [], int); int length(char str[], int index)
{
int main()
if (str[index] == '\0')
{
char str[20]; {
int count; return 0;
}
printf("Enter any string :: "); return (1 + length(str, index + 1));
scanf("%s", str); }
count = length(str, 0);
printf("The length of string=%d.\n",count);
return 0;
Output:
}
Enter any string :: Manipal
The length of string= 7
65
Extra Problem-Binary Search
#include<stdio.h>
int binarySearch(int x[],int element,int start,int end);
int main(){
int x[20],n,i,index,start=0,end,element;
printf("Enter number of elements: ");
scanf("%d",&n);
end = n;
printf("Enter array elements: ");
for(i=0;i<n;i++){
scanf("%d",&x[i]);
}
printf("Enter the element to search: ");
scanf("%d",&element);
index = binarySearch(x,element,start,end-1);
if(index == -1)
printf("Element Not Found.\n");
else
printf("Element found at index : %d\n",index);
return 0;
66
}
Extra Problem-Binary Search
int binarySearch(int x[],int element,int start,int end){
int mid,noOfElements,i;
mid = (int)(start+end)/2;
if(start > end)
return -1;
if(x[mid] == element)
return mid;
else if(x[mid] < element){
start = mid+1;
binarySearch(x,element,start,end);
}
else{
start = 0;
end = mid-1; Output:
binarySearch(x,element,start,end); Enter number of
} elements: 5
Enter array elements: 1
2345
} Enter the element to
search: 3
67
Element found at
Extra Problem- Recursive Sorting
Base Case:
if length of the list (n) = 1
No sorting, return
Recursive Call:
1. Find the smallest element in the list and
place it in the 0th position
2. Sort the unsorted array from 1.. n-1
sortR(&list[1], n-1)
68
Extra problem-Sorting
{-2,33,0,2,4} sort(&list[1],4)
{-2,0,33,2,4} sort(&list[1],3)
{-2,0,2,33,4} sort(&list[1],2)
{-2,0,2,4,33} sort(&list[1],1)
71
Reversing a given number ‘n’
int Reverse(int); //prototype int Reverse(int num)
{
int main() int rev=0;
{ int digit;
int n,r;
printf("Enter a number : \n“); while(num!=0)
scanf(“%d”, &n); {
digit = num % 10;
r= Reverse(n); rev = (10 * rev) + digit;
printf(“ reversed no=%d“,r) num = num/10;
}
return 0; return (rev);
} }
72
Check whether given number is prime or not
int IsPrime(int); //prototype int IsPrime(int num) //prime
check
int main() { {
int n; int p=1;
for(int j=2;j<=num/2;j++)
printf(“Enter a number : “); {
scanf(“%d”,&n); if(num%j==0)
if (IsPrime(n)) {
Printf(“%d is a prime no”,n); p=0;
else break;
Printf(“%d is not a prime no”,n); }
return 0; }
} return p;
}
73
First n Fibonacci number generation
void fibFn(int); //prototype void fibFn(int lim) { //fib generation
int i, first, sec, next;
int main() { if (lim<=0)
printf("limit should be +ve.\n“);
int n;
else
printf("Enter the limit ”); {
scanf(“%d”,&n); printf("\nFibonacci nos\n“);
fibFn(n); //function call first = 0, sec = 1;
return 0; for (i=1; i<=lim; i++) {
} printf(“%d”, first)
next = first + sec;
first = sec;
sec = next;
}
}
}
74