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

Unit 7 Functions

Uploaded by

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

Unit 7 Functions

Uploaded by

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

Functions

Prepared By: Rajan Kumar KC 1


Function
 A function is defined as a self-contained block of
statements that performs a particular task or job.
 Every C program has one or more functions.
 The function main() is always present in every C
program which is executed first and other functions
are optional.

2
Advantages of using Functions
1. Functions increases code reusability by avoiding
rewriting of same code over and over.
2. If a program is divided into multiple functions,
then each function can be independently developed.
So program development will be easier.
3. Program development will be faster.
4. Program debugging will be easier.
5. Function reduces program complexity.
6. Easier to understand logic involved in the
program.
7. Recursive call is possible through function.
3
Two types of functions:
 Library functions (Built-in functions): These functions
are provided in the programming language and we can
directly use them as required. However, the function’s
name, return type, number of arguments and types
must be known in advance. For e.g. printf(), scanf(),
sqrt(), getch(), etc.
 User-defined functions: These functions are written by
the user. The user selects the name of the function,
return type, number of arguments and types.
 Note: main() is a user defined function. However
the name of the function is defined or fixed by the
programming language.
4
Components of Functions
Function Prototype
Function Call
Function Definition

Prepared By: Rajan Kumar KC 5


Function Definition
 The function definition consists of the whole description and code of a function.
 It tells what the function is doing and that are its inputs and outputs.
 A function definition consists of two parts - a function header and a function body.
 The general syntax of a function definition is:
return_type func_name(type1 arg1, type2 arg2, ………….)
{
local variables declarations;
statements;
return(expression);
}
• The first line in the function definition is known as the function header and after
this the body of the function is written enclosed in curly braces.
• The return_type denotes the type of the value that will returned by the function.
The return_type is optional and if omitted, it is assumed to be int by default. A
function can return either one value or no value.
• func_name specifies the name of the function and it can be any valid C identifier.
6
Prepared By: Rajan Kumar kc
Function definition contd..
 The collection of program statements that describes
the specific task to be done by the function is called a
function definition.
 Function definition consists of function header
(function’s name, return type, and number and types
of arguments) and function body (block of code or
statements enclosed in parentheses).
 Syntax:
return_type function_name(data_type variable1, …,data_type variableN)
{
…………………;
…………………;
statements;
}
7
Function definition…
 return_type is optional. The default value is integer.
 Whenever return_type is provided, a value must be
returned using return statement except for void case.
 function_name is a user-defined name given to the
function. (Same as identifier naming)
 variable1, …,variableN are called formal arguments or
formal parameters that are passed to the function. Also
these are local variables for the function.

8
Example of function definition:
#include <stdio.h>
int add(int c, int d)
{
int sum;
sum = c+d;
return sum;
}
void main()
{
………;
}

9
Function call
 A function is called by simply writing its name
followed by the argument list inside the
parentheses.
func_name(arg1, arg2, arg3,….);
• These arguments arg1,arg2,arg3,…are called actual
arguments.
• Here func_name is known as the called function
while the function in which this function call is
placed is known as the calling function.

Prepared By: Rajan Kumar kc 10


Calling a function through main() cont.
 A function can be called by specifying the function’s
name, followed by a list of arguments enclosed in
parentheses and separated by commas.
 For example, the function add() can be called with two
arguments from main() function as:
add(a, b);
 These arguments appearing in the function call are
called actual arguments or actual parameters.
 In this case, main() is called calling function and add()
is called called function.
11
Important
Calling a function through main()…
 Note:
 In function call, there must be one actual argument for
each formal argument. This is because the value of actual
argument is transferred into the function and assigned to
the corresponding formal argument.
 If a function returns a value, the returned value can be
assigned to a variable of data type same as return type of
the function to the calling function.
 When a function is called, the program control is passed to
the function and once the function completes its task, the
program control is transferred back to the calling function.

12
#include <stdio.h>
#include <conio.h> W h e n va l u e i s
int add(int c, int d)
b e i n g re t u r n e d by
{
int sum; a function,
sum = c+d; c a p t u re i t i n
return sum; main() function
} as:
void main()
{
int a=50,b=100, x;
x=add(a, b);
printf(“%d”, x);
getch();
}
Output: 150
13
void add(int c, int d)
{
int sum; W h e n va l u e i s n o t
sum = c+d; b e i n g re t u r n e d
printf(“%d”, sum); ( i . e . re t u r n t y p e i s
} vo i d ) , p r i n t
void main() within the
{ function, if
int a=50,b=100; needed.
add(a, b);
getch();
}

14
Write functions to add,
subtract, multiply and
divide two numbers a and b.

15
// Combination Problem
#include <stdio.h>
long factorial(int n)
{
long fact=1;
int i;
for(i=1;i<=n;i++)
fact *= i;
return fact;
}
void main()
{
long f1=1,f2=1,f3=1,comb;
int n, r;
printf("\nEnter n and r:");
scanf("%d %d",&n,&r);
f1=factorial(n);
f2=factorial(n-r); calculates nCr = n! / [(n - r)! * r!] using the factorial function]
f3=factorial(r);
comb=f1/(f2*f3);
printf("\n The combination is: %ld", comb);
}
Output: Enter n and r:5 3

The combination is: 10

16
Function Prototype/declaration
 The calling function needs information about the called
function. The function declaration is also known as the
function prototype, and it informs the compiler about
the following three things:
1. Name of the function
2. Number and type of arguments received by the
function
3. Type of value returned by the function
 Function declaration tells the compiler that a function
with these features will be defined and used later in the
program.

Prepared By: Rajan Kumar KC 17


Function Prototype or Declaration
 The function prototype is a model or blueprint of the
function.
 The function prototype is necessary if a function is
used before function is defined.
 When a user-defined function is defined before the
use, function prototype is not necessary.
 Syntax:
return_type function_name(data_type1, …,data_typeN);
 E.g.
void add(int, int);

18
#include <stdio.h>
#include <conio.h>
int add(int, int); //Function Prototype
void main()
{
int a=12,b=5,x;
clrscr();
x=add(a,b);
printf("%d",x);
getch();
}
int add(int c, int d)
{
int sum;
sum=c+d;
return sum;
}
Output:- 17

19
Example: Components of functions
#include <stdio.h>
void sum(int, int); //function declaration (Prototype)
void main()
{
int a, b;
printf("Enter two numbers\n");
scanf("%d%d",&a, &b);
sum(a,b); //function call
}
void sum(int x, int y)
{ //function definition
int s;
s=x+y;
printf("Sum =%d", s);
}

Prepared By: Rajan Kumar kc 20


The return Statement
The return statement serves two purposes:
1. It immediately transfers the control back to the calling
function (i.e. no statements within the function body
after the return statement are executed).
2. It returns the value to the calling function.
Syntax:
return (expression);
where expression, is optional and, if present, it must
evaluate to a value of the data type specified in the
function header for the return_type.
Note: When nothing is to be returned, the return_type in the
function definition is specified as void. For void
return_type, return statement is optional.
21
/*Program using function to find the greatest number among three numbers*/
#include <stdio.h>
int greater(int, int);
void main()
{
int a, b, c, d, e;
printf("\n Enter three numbers:");
scanf("%d %d %d",&a,&b,&c);
d=greater(a, b);
e=greater(d, c);
printf("\n The greatest number is:%d", e);
}
int greater(int x, int y)
{
if(x>y)
return x;
else
return y;
22
Function parameters
 Function parameters are the means for
communication between the calling and the called
functions.
 Two types: formal parameters and actual parameters.
 Formal parameters are given in the function definition
while actual parameters are given in the function call.
 The name of formal and actual parameters need not
be same but data types and the number of parameters
must match.

23
What happens when…???
➢ Actual arguments are less than the formal arguments
in a function.
➢ Data type of one of the actual arguments does not
match with the data type of the corresponding formal
argument.
➢ Data type of one of the arguments in a prototype does
not match with the type of the corresponding formal
parameter in the header.
➢ The order of actual parameters in the function call is
different from the order of formal parameters in a
function where all parameters are of the same type.
➢ The type of expression used in return statement does
not match with the type of the function.
24
Assignment
 Write a function which receives a float number and an
integer number from main(), finds the product of
these two and returns the product which is printed in
main().
 Write a function AreaOfCircle() which accepts radius
of float value and returns the area of the circle. Use
this function to calculate area of two circles having
different radii. (Use symbolic constant to define PI)

25
Problem
 Write and test the following power() function that
returns x raised to the power n, where n can be any
integer:
double power (double x, int p)

26
#include <stdio.h>
#include <conio.h>
double power(double x, int p)
{
double a=1;
if(p==0)
return 1;
else if(p>0)
{
while(p!=0)
{
a=a*x;
p--;
}
return a;
}
else
{
while(p!=0)
{
a=a/x;
p++;
}
return a;
}
}

27
void main()
{
int p;
double x, z;
printf("Enter x and p:\t");
scanf("%lf %d", &x, &p);
z=power(x, p);
printf("\n x raised to power n is:%lf", z);
}
Output:-
Enter x and p: 3 2
x raised to power n is:9.000000
28
Types of Functions
1) Functions with no arguments and no return values
2) Functions with arguments but no return values
3) Functions with arguments and return values

29
Functions with no arguments and
no return values
 When a function has no arguments, it does not receive
any data from the calling function.
 When a function does not return a value, the calling
function does not receive any data from the called
function.
 Thus, there is no data transfer between the calling
function and the called function.
 Syntax: void function_name()
{
/* body of function */
}
30
//EXAMPLE
#include <stdio.h>
void add()
{
int a, b, sum;
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum=a+b;
printf("\nThe sum is:%d", sum);
}
void main()
{
add();
}

31
Functions with arguments but no
return value
 This type of function has arguments and receives the
data from the calling function.
 But after the function completes its task, it does not
return any values to the calling function.
 Syntax:
void function_name(argument_list)
{
/* body of function */
}

32
//EXAMPLE
#include <stdio.h>
void add(int a, int b)
{
int sum;
sum=a + b;
printf("\n The sum is:%d", sum);
}
int main()
{
int a,b;
printf("\n Enter two numbers:");
scanf("%d %d",&a,&b);
add(a, b);
return 0;
}

Output: Enter two numbers: 4 2


The sum is:6

33
Functions with arguments and
return values
 This type of function has arguments and receives the data
from the calling function.
 However, after the task of the function is complete, it
returns the result to the calling function via return
statement.
 So, there is data transfer between called function and
calling function using return values and arguments.
Syntax: return_type function_name(argument_list)
{
/* body of function */
}

34
//EXAMPLE
#include <stdio.h>
int add(int a, int b)
{
int sum;
sum=a + b;
return sum;
}
void main()
{
int a, b, x;
printf("\n Enter two numbers:");
scanf("%d %d", &a, &b);
x=add(a, b);
printf("\n The sum is:%d", x);
}
Output: Enter two numbers: 4 5
The sum is: 9

35
PROBLEM
 Write a function to add, subtract, multiply
and divide two complex numbers (x + i*y)
and (a + i*b).

36
#include <stdio.h>
void add(int x, int y, int a, int b)
{
printf("\n The addition of the complex numbers is:%d+i%d",x+a,y+b);
}

void subtract(int x, int y, int a, int b)


{
printf("\n The subtaction of the complex numbers is:%d+i%d",x-a,y-b);
}

void multiply(int x, int y, int a, int b)


{
int real, img;
real=(a*x-b*y);
img=(a*y+b*x);
printf("\n The multiplication of the complex numbers is:%d+i%d", real, img);
}

37
void main()
{
int x, y, a, b;
printf("\n Enter Ist complex number of the form (x+iy):");
scanf("%d+i%d", &x, &y);
printf("\n Enter 2nd complex number of the form (a+ib):");
scanf("%d+i%d", &a, &b);
add(x, y, a, b);
subtract(x, y, a, b);
multiply(x, y, a, b);
}
Output:- Enter Ist complex number of the form (x+iy): 3+i4
Enter 2nd complex number of the form (a+ib): 1+i2

The addition of the complex numbers is: 4+i6


The subtaction of the complex numbers is: 2+i2
The multiplication of the complex numbers is: -5+i10

//Write function for division yourself


38
PROBLEM
 Write a function to solve a quadratic equation
ax2+bx+c=0. The inputs to the function are the values
a, b and c and the outputs of the function should be
stored in variable names p and q appropriately
declared.

39
#include <stdio.h>
#include <conio.h>
#include <math.h>
void quad(float, float, float);
void main()
{
float a, b, c;
clrscr();
printf("\n Enter values a, b and c of the quadratic
equation:");
scanf("%f %f %f", &a, &b, &c);
quad(a, b, c);
getch();
}

40
void quad(float a, float b, float c)
{
float p, q;
float d;
d = b*b-4*a*c;

if(d<0)
{
printf("\n Imaginary Roots.");
d = sqrt(fabs(d)); //compute absolute value of discriminant
p = -b/(2*a);
q = d/(2*a);
printf("\nRoot1 = %.2f +i %.2f",p,q);
printf("\nRoot2 = %.2f -i %.2f",p,q);
}
else
{
printf("\n Roots are real.");
d = sqrt(d);
p = (-b+d)/(2*a);
q = (-b-d)/(2*a);
printf("\nRoot1 = %.2f \t Root2 = %.2f",p,q);
}
}
Output:- Enter values a, b and c of the quadratic equation: 1 2 3

Imaginary Roots.
Root1 = -1.00 +i 1.41
Root2 = -1.00 -i 1.41

41
Types of function calls
Function calls are divided in two ways according to
how arguments are passed in the function.
1. Pass arguments by value (Function call by Value)
2. Pass arguments by address (Function call by
Reference)

42
Passing by Value
 When values of actual arguments are passed to the
function as arguments, it is known as passing by value.
 Here, the value of each actual argument is copied into
corresponding formal argument of the function
definition.
 Note: The contents of the actual arguments in the
calling function are not changed, even if they are
changed in the called function.

43
#include <stdio.h>
void swap(int, int);
void main()
{
int a=50, b=100;
printf("\n Before swap function call: a=%d and b=%d", a, b);
swap(a,b);
printf("\n After swap function call: a=%d and b=%d", a, b);
}
void swap(int x, int y)
{
int temp;
temp=x;
x=y;
y=temp;
printf("\n Values within swap: x=%d and y=%d", x, y);
}
Output: Before swap function call: a=50 and b=100
Values within swap: x=100 and y=50
After swap function call: a=50 and b=100

44
Passing by Address
 When addresses of actual arguments are passed to the
function as arguments (instead of values of actual
arguments), it is known as passing by address.
 Here, the address of each actual argument is copied
into corresponding formal argument of the function
definition.
 In this case, the formal arguments must be of type
pointers.
 Note: The values contained in addresses of the actual
arguments in the calling function are changed, if they
are changed in the called function.
45
What is a pointer???
 A pointer is a variable that stores the memory address
of a variable.
 Pointer naming is same as variable naming and it is
declared in the same way like other variables but is
always preceded by * (asterisk) operator.
 E.g. int b, *a; //pointer declaration
a=&b; /* address of b is assigned to
pointer variable a */

46
#include <stdio.h>
void swap(int *, int *);
int main()
{
int a=50, b=100;
printf("\n Before swap function call: a=%d and b=%d", a, b);
swap(&a, &b);
printf("\n After swap function call: a=%d and b=%d", a, b);
}
void swap(int *x, int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
printf("\n Values within swap: x=%d and y=%d", *x, *y);
}

Output:
Before swap function call: a=50 and b=100
Values within swap: x=100 and y=50
After swap function call: a=100 and b=50
47
PROBLEM
 Given three variables x, y, and z, write a function to
circularly shift their values. In other words, if x=5, y=9,
and z=8, after circular shift y=5, z=9, and x=8. Call the
function with variables a, b, and c to circularly shift
their values.

48
#include <stdio.h>
void circularshift(int *, int*, int*);
int main()
{
int x=5, y=9, z=8;
printf("\nBefore circular shift-x, y and z are:%d\t%d\t%d",x,y,z);
circularshift(&x,&y,&z);
printf("\nAfter circular shift-x, y & z are:%d\t%d\t%d",x,y,z);
}
void circularshift(int *x, int *y, int *z)
{
int temp1, temp2;
temp1=*x;
temp2=*y;
*x=*z;
*y=temp1;
*z=temp2;
} Call by value…do it yoursel
Output:
Before circular shift-x, y and z are: 5 9 8
After circular shift-x, y & z are: 8 5 9

49
One more type of function:
Functions that return multiple values
 A return statement can return only one value.
 When we need to return more than one value from a
function…………???
 We can achieve this by using the arguments not only
to receive information but also to send back
information to the calling function.
 The arguments that are used to send out information
are called output parameters.
 The mechanism of sending back information through
arguments is achieved using what are known as the
address operator (&) and the indirection operator (*).
50
#include<stdio.h>
void fun(int, int, int *,int *);
int main()
{
int x=100,y=50,s,d;
fun(x, y, &s, &d);
printf("s=%d \td=%d", s, d);
}
void fun(int a, int b, int *sum, int *diff)
{
*sum=a + b;
*diff=a-b;
}

Output: s = 150 d = 50

51
Recursive function
 When a function calls itself directly or indirectly, it is called
recursive function and the process of calling itself is called
recursion.
 E.g.
#include <stdio.h>
#include <conio.h>
void main()
{
printf("Hey! This is direct recursion.\n");
main();
getch();
}
Output: Hey! This is direct recursion (infinite times)
52
 E.g.
#include <stdio.h>
void printline();
void main()
{
printf("Hey! This is not direct recursion.\n");
printline();
}
void printline()
{
printf("Indirect Recursion\n");
main();
}
Output:Hey! This is not direct recursion.
Indirect Recursion (alternate display infinite times)

53
Recursive function
 To solve a problem using recursive method, two
conditions must be satisfied:
1) Problem should be written or defined in terms of its
previous result.
2) Problem statement must include a terminating
condition, otherwise the function will never
terminate. This means that there must be an if
statement somewhere in the recursive function to
force the function to return without the recursive call
being executed.

54
//Factorial of a number using recursion
#include <stdio.h>
long int factorial(int n)
{
if(n==1)
return 1;
else
return (n*factorial(n-1));
}
void main()
{
int number;
long int x;
printf("Enter a number whose factorial is needed:\t");
scanf("%d", &number);
x=factorial(number);
printf("\n The factorial is:%ld", x);
}
Output:- Enter a number whose factorial is needed: 5
The factorial is: 120 55
How above problem is recursive?
 Self-call: The function calls itself (factorial(n-1)).
 Problem Reduction: Each recursion call reduces the
size of the problem by 1.
 Base Case: Prevents infinite recursion by stopping
when n==1.

56
//Write a program to find ab using recursion.
#include<stdio.h>
int recursion(int, int);
void main()
{
int a, b, z;
printf("\n Enter a and b:\t");
scanf("%d %d",&a,&b);
z=recursion(a,b);
printf("\n %d raised to power %d=%d", a, b, z);
}
int recursion(int x, int y)
{
if(y==1)
return x;
else
return (x*recursion(x,y-1));
}
Output:- Enter a and b: 2 4 57
Storage Class
 Variables in C are categorized into four different storage
classes according to the scope and lifetime of variables:
1. Automatic variables
2. External variables
3. Static variables
4. Register variables
Note:
 The scope of variable determines over what part(s) of the
program a variable is actually available for use (active).
 Lifetime refers to the period of time during which a
variable retains a given value during execution of a
program (alive).

58
 Note:
 Variables can also be broadly categorized, depending
on the place of their declaration, as internal (local) or
external (global).
 Local variables are those which are declared within a
particular function, while global variables are declared
outside of any function.

59
Local Variable (Automatic or
Internal Variable)
 Automatic variables are always declared inside a function
or block in which they are to be used.
 They are created when the function is called and destroyed
automatically when the function is exited, hence the name
is automatic.
 The keyword auto is used for storage class specification
although it is optional.
 Initial value: garbage
 Scope: local to the block where the variable is defined
 Lifetime: till the control remains within the block where
variable is defined
60
#include <stdio.h>
void function1()
{
auto int m=20;
printf("\n m=%d", m);
}

void main()
{
auto int m=10; Note: Use of keyword “auto” is optional
printf("m=%d", m);
function1();
}
Output: m=10
m=20

61
#include <stdio.h>
void main()
{
int m=10;
printf("m=%d", m);
{
int m=20;
printf("\n m=%d", m);
}
printf("\n m=%d", m);
}
Output:- m=10
m=20
m=10
//Two variables can have same name in different scope

62
//What happens?????
#include <stdio.h>
void main()
{
int m=10;
printf("m=%d",m);
{
int mn=20;
printf("\n mn=%d",mn);
}
printf("\n mn=%d",mn);
printf("\n m=%d",m); when you attempt to print mn outside
} the inner block, the compiler will raise an
error, saying that mn is undeclared in
that scope. 63
Global Variable (External Variable)
 The global variables are declared outside any block or
function.
 These variables are both alive and active throughout
the entire program.
 Unlike local variables, global variables can be accessed
by any function in the program.
 Initial value: zero
 Scope: global (i.e. throughout the program (multifile
too))
 Lifetime: throughout program’s execution

64
#include <stdio.h> #include <stdio.h>
#include <conio.h> #include <conio.h>
int a; void main()
void main() {
{ int a;
clrscr(); clrscr();
printf("%d", a); printf("%d", a);
getch(); getch();
} }
//Global Variable //Local Variable

65
#include <stdio.h>
int a=100;
void function()
{
a=200;
printf("%d\n", a++);
}
void main()
{
printf("%d\n", a);
function();
printf("%d", a);
}
Output: 100
200
201

66
 Description
Here, once a variable is declared as global, any
function can use it and change its value. Then
subsequent functions can reference only that new
value. As the global variable a is recognized by main()
as well as function(), so values are printed as 100, 200
and 201.

Note: Care should be taken while using global variables.


Only those variables should be declared as global
which are to be shared among different functions
when it is inconvenient to pass them as parameters.

67
 Question: Since global variables are declared outside
of any function, can you declare a global variable
anywhere in the program and use it among many
different functions?

 Ans: No. A global variable is visible only from the point


of declaration to the end of the program.

 Solution: declare variable using storage class extern in


all functions

68
#include <stdio.h> #include <stdio.h>
#include <conio.h> #include <conio.h>
void function() void function()
{ {
y=y+1; y=y+1;
printf("%d\n", y); printf("%d\n", y);
} }
void main() int y;
{ void main()
y=100; {
clrscr(); y=100;
function(); clrscr();
getch(); function();
} getch();
int y; }
//Error //Error

69
Multifile Program
 In real-life programming environment, more than one
source files are compiled separately and linked later to
form an executable code.
 Multiple source files can share a variable if it is
declared as an external (global) variable appropriately
as shown in coming slide:

70
//file1.c saved in C:\TC\BIN
#include <stdio.h>
#include <conio.h>
#include "file2.c"
void fun2();
int m;
void fun1()
{
m=1;
printf("\nThis is fun1 in file1.c where m=%d",m);
}
void main()
{
clrscr();
printf("\nThis is main where m=%d",m);
fun1();
fun2();
getch();
}

71
//file2.c saved in C:\TC\BIN
extern int m;
void fun2()
{
m=2;
printf("\n This is fun2 in file2.c where m=%d", m);
}

/*A multifile global variable should be declared


without the extern keyword in one (and only one)
of the files*/

72
Static Variable
 As the name suggests, the value of static variables
persists till the end of the program.
 A variable is declared static using the keyword static:
static int x;
 A static variable may be either an internal type or an
external type, depending on the place of declaration.
 Initial value: zero (initialized only once)
 Scope: local (within the function) or global (within the
program (single file))
 Lifetime: throughout the program for local as well as
global static variables

Prepared By: Rajan Kumar kc 73


Static Variable…
Q.1) What is the difference between internal static
variable and auto variable?
Ans: The lifetime of internal static variables is
throughout the program. So they retain values
between function calls. Also internal static variables
are initialized only once.

Q.2) What is the difference between external static


variable and extern variable?
Ans: The static external variable is available only within
the file where it is defined whereas external variable
can be accessed by other files as well.

74
#include <stdio.h> #include <stdio.h>
void stat() void stat()
{ {
int x=0; static int x=0;
x=x+1; x=x+1;
printf("x=%d\n", x); printf("x=%d\n", x);
} }
int main() void main()
{ {
int i; int i;
for(i=1;i<=3;i++) for(i=1;i<=3;i++)
stat(); stat();
} }
Output: Output:
x=1 x=1
x=1 x=2
x=1 x=3
75
VVI. Problem
 Write a program to display the reverse of a number
using recursion.
❖ Take a look at static variable use in recursion

Prepared By: Rajan Kumar KC 76


#include<stdio.h>
int rev(int);
void main()
{
int n, r;
printf("\n Enter number you want to reverse:");
scanf("%d", &n);
r=rev(n);
printf("\n The reverse of the number is:%d", r);
}
int rev(int num)
{
static int sum=0; //sum should retain its previous value
int r;
if(num>0) //stopping condition
{
r=num % 10;
sum=sum*10+r;
rev(num/10); //recursive function call
}
return sum;
}
Output: Enter number you want to reverse: 214
The reverse of the number is: 412
77
Register Variable
 Normally, variables are stored in memory.
 However, we can instruct the compiler that a variable
should be kept in one of the CPU’s registers, instead of
keeping in the memory.
 Use: A register access is much faster than a memory
access. So keeping frequently accessed variables (e.g.
loop control variables) in the register will help faster
execution of the program.
 A register variable is declared using register keyword:
 Example: register int i;
78
Register Variable…
 Register variables are always declared inside a function
or block.
 They are allocated space upon entry to a block; and the
storage is freed when the block is exited.
 Initial value: garbage
 Scope: only in that function or block
 Lifetime: until end of function or block

79
#include <stdio.h>
int main()
{
register int i;
for(i=1; i<15; i++)
printf(" %d\t", i);
return 0;
}
Output:
1 2 3 4 5 6 7 8 9
10 11 12 13 14
80
Passing Array to a Function
 It is possible to pass the value of an array element or an
entire array as an argument to a function.
 Passing array elements is similar to passing variables
except that array subscripts are needed in function
call.

81
//Passing elements of an array
#include <stdio.h>
void display(int, int);
int main()
{
int nums[5]={1,2,3,4,5};
printf("\n The array elements passed are:\n");
display(nums[3], nums[4]);
}
void display(int n, int m)
{
printf("%d\t %d", n, m);
}
Output: The array elements passed are:
4 5

82
Passing 1-D Array to a Function…
 To pass an entire array to a function, the array name is
given without square brackets or subscripts, as an actual
argument in function call statement.
 In the function definition, the corresponding formal
argument must declare an array with a pair of empty square
brackets (without specifying the size of the array, although
it doesn’t matter) for a One-Dimensional array.
 The function prototype must show that the argument is an
array.
 Syntax for function call: function_name(array_name);
 Syntax for function prototype:
return_type function_name(data_type array_name[]);
83
#include <stdio.h>
void display(int a[]);
void main()
{
int nums[5]={1,2,3,4,5};
printf("\n The contents of array is:\n");
display(nums);
}
void display(int n[])
{
int i;
for(i=0;i<5;i++)
printf("%d\t", n[i]);
}
Output: The contents of array is:
1 2 3 4 5
84
Problem
 Write a function to sort a set of n numbers in
ascending order of magnitude. How would this routine
be called?

85
#include <stdio.h>
#define SIZE 100
void sort(int nums[], int);
void main()
{
int nums[SIZE], i, n;
printf("\n How many numbers you want to sort(<100)?:\t");
scanf("%d", &n);
for(i=0;i<n;i++)
scanf("%d", &nums[i]);
sort(nums, n); //routine (function) call
}

86
void sort(int nums[], int n)
{
int i, j, temp;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(nums[i]>nums[j])
{
temp=nums[i];
nums[i]=nums[j];
nums[j]=temp;
}
}
}
printf("\n The numbers in ascending order are:\n");
for(i=0;i<n;i++)
printf("\t%d", nums[i]);
}
Output: How many numbers you want to sort(<100)?: 10
3 5 6 1 7 15 13 14 8 9

The numbers in ascending order are:


1 3 5 6 7 8 9 13 14 15

Prepared By: Rajan Kumar KC 87


Passing 2-D Array to a Function…
Rules
1. The function must be called by passing only the
array name.
2. In the function definition, we must indicate that
the array has two dimensions by including two
sets of brackets.
3. The size of the second dimension must be
specified.
4. The prototype declaration should be similar to
the function header.
88
//Program to display a matrix
#include <stdio.h>
void display(int rix[][2]);
void main()
{
int matrix[2][2], i, j;
clrscr();
printf("Input matrix elements:\t");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
scanf("%d", &matrix[i][j]);
}
display(matrix);
getch();
}
void display(int mat[][2])
{
int i, j;
printf("\n The matrix is:\n");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
printf(" %d\t", mat[i][j]);
printf("\n");
}
} 89
Write a program to read a matrix of
order m*n. Pass this matrix to a
function which increases each
element of the matrix by 2.

90
#include<stdio.h>
#define M 3
#define N 3
void increase_by_2(int rix[][N]);
void main()
{
int matrix[M][N], i, j;
printf("Input matrix elements of order %d*%d:\n", M, N);
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
scanf("%d", &matrix[i][j]);
}

printf("\n The input matrix is:\n");


for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
printf(" %d\t", matrix[i][j]);
printf("\n");
}

increase_by_2(matrix);
printf("\n The output matrix is:\n");
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
printf(" %d\t", matrix[i][j]);
91
printf("\n");
void increase_by_2(int mat[][N])
{
int i, j;
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
mat[i][j]=mat[i][j]+2;
}
}
Output:-
Input matrix elements of order 3*3:
3 5 7 8 1 3 8 6 2
The input matrix is:
3 5 7
8 1 3
8 6 2
The output matrix is:
5 7 9
10 3 5
92
10 8 4
The thing to remember…
 When an entire array is passed to a function and if that
function changes the values of array elements, then these
changes are actually made to the original array that is
passed to the function.
 This means that when an entire array is passed as an
argument, the contents of the array are not copied into the
formal parameter; instead, information about the
addresses of array elements are passed on to the function.
 Thus, any changes made to the array elements by the
function are truly reflected in the original array in the
calling function.
 However, this does not apply when an individual array
element is passed as an argument.

93
PROBLEM
 Write a function which will take as its input a matrix of
size (m*n), where m<10, n<5 and returns the same
matrix with all its elements replaced by absolute
values.

94
#include<stdio.h>
#include <math.h>
#define M 10
#define N 5
void absolute(int rix[][N], int, int);
void main()
{
int matrix[M][N], i, j, m, n;
printf("Input size of matrix up to %d*%d:\n",M-1,N-1);
scanf("%d %d", &m, &n);
if(m>9||n>4)
{
printf("\n The order is out of range.");
exit(0);
}
printf("\n Enter matrix elements of order %d*%d:\n", m, n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d", &matrix[i][j]);
}

95
printf("\n The matrix is:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf(" %d\t",matrix[i][j]);
printf("\n");
}

absolute(matrix,m,n);
printf("\n The absolute matrix is:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
}

96
void absolute(int mat[][N], int m, int n)
{
int i, j;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
mat[i][j]=abs(mat[i][j]);
}
}
}
Output:- Input size of matrix up to 9*4:
3 3

Enter matrix elements of order 3*3:


1 -2 3 -4 6 -5 7 9 -6

The matrix is:


1 -2 3
-4 6 -5
7 9 -6

The absolute matrix is:


1 2 3
4 6 5
7 9 6 97
Problem
 Write a function named addarrays that accepts two
integer arrays that are of the same size. The function
should add each element in the arrays together and
place the values in a third array. That is:
First element of 3rd array = First element of 1st array +
First element of 2nd array
Second element of 3rd array = Second element of 1st
array + Second element of 2nd array
And so on.

98
#include<stdio.h> }
#define M 10
#define N 10 printf("\n Enter the elements of second matrix:\t");
void addarrays(int [][N],int [][N], int, int); for(i=0;i<p;i++)
{
int main() for(j=0;j<q;j++)
{ {
int matrix1[M][N],matrix2[M][N]; scanf("%d",&matrix2[i][j]);
int i, j; }
int m, n, p, q; }
printf("\n Enter order of first matrix (less than addarrays(matrix1,matrix2,m,n);
10*10):\t"); }
scanf("%d %d",&m,&n);
printf("\n Enter order of second matrix (less than void addarrays(int mat1[][N], int mat2[][N], int x, int y)
10*10):\t"); {
scanf("%d %d", &p, &q); int i,j;
if((m!=p) || (n!=q)) int add[M][N];
{
printf("\n The matrices are unsuitable for for(i=0;i<x;i++)
addition.\n");
//exit(); {
} for(j=0;j<y;j++)
{
printf("\n Enter the elements of first matrix:\t"); add[i][j]=mat1[i][j]+mat2[i][j];
for(i=0;i<m;i++) }
{ }
for(j=0;j<n;j++)
{
scanf("%d",&matrix1[i][j]);
}

99
// Print the resultant matrix Output:
printf("\n The resultant Enter order of first matrix (less
than 10*10): 2 2
matrix is:\n");
Enter order of second matrix
for (i = 0; i < x; i++) { (less than 10*10): 2 2
for (j = 0; j < y; j++) {
printf("%d\t",add[i][j]); Enter the elements of first
matrix: 2 5 7 9
}
printf("\n"); Enter the elements of second
} matrix: 3 6 8 1
}
The resultant matrix is:
5 11
15 10

100
PROBLEM
 Write a function to multiply two n*n matrices.

101
#include <stdio.h>
#define N 3
void multiply(int rix1[][N], int rix2[][N]);
void main()
{
int matrix1[N][N],matrix2[N][N],i,j;
printf("Input first matrix elements of order %d*%d:\n", N, N);
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
scanf("%d",&matrix1[i][j]);
}

printf("\n The first matrix is:\n");


for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
printf(" %d\t",matrix1[i][j]);
printf("\n");
}

102
printf("Input second matrix elements of order %d*%d:\n", N,
N);
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
scanf("%d", &matrix2[i][j]);
}

printf("\n The second matrix is:\n");


for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
printf(" %d\t",matrix2[i][j]);
printf("\n");
}
multiply(matrix1,matrix2);
}//main ends here
103
//multiply function
void multiply(int mat1[][N],int mat2[][N])
{
int multiply[N][N], i, j, k, row_mul_col=0;
for(i=0;i<N;i++) //first row
{
for(j=0;j<N;j++) //second column
{
for(k=0;k<N;k++) //first column or second row
{
row_mul_col=row_mul_col+mat1[i][k]*mat2[k][j];
}
multiply[i][j]=row_mul_col;
row_mul_col=0;
}
}
printf("\n The matrix after multiplication is:\n");
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
{
printf("%d\t", multiply[i][j]);
}
printf("\n");
}
}

104
Output
 Input first matrix elements of order 3*3:
2 4 6 8 1 3 9 3 5

 The first matrix is:


 2 4 6
 8 1 3
 9 3 5
 Input second matrix elements of order 3*3:
9 6 4 3 1 2 5 7 8

 The second matrix is:


 9 6 4
 3 1 2
 5 7 8

 The matrix after multiplication is:


 60 58 64
 90 70 58
 115 92 82
For example, to calculate the element in the first row and first column of the result:
(2*9)+(4*3)+(6*5)=18+12+30=60
Similarly, others…

Prepared By: Rajan Kumar KC 105


PROBLEM
 Write a function to multiply a square matrix by a vector. Assume
a n*n matrix and a n component vector. The call would give the
size of the matrix and the names of the matrix and a vector.

Note:
Vectors are a type of matrix having only one column or one row.
There are two types of vectors: column vectors and row
vectors. For example, matrix a is a column vector, and matrix a'
is a row vector.
11
a = 22 a' = 11 12 33
33

106
#include <stdio.h>
#define N 3
void multiply(int rix[][N], int tor[]);
void main()
{
int matrix[N][N],vector[N],i,j;
clrscr();
printf("Input matrix elements of order %d*%d:\n", N, N);
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
scanf("%d", &matrix[i][j]);
}

printf("\n The matrix is:\n");


for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
printf(" %d\t", matrix[i][j]);
printf("\n");
}

107
printf("Input vector of %d components:\n", N);
for(i=0;i<N;i++)
scanf("%d", &vector[i]);

printf("\n The %d component vector is:\n", N);


for(i=0;i<N;i++)
{
printf("%d\t", vector[i]);
}

multiply(matrix, vector);
}

108
void multiply(int mat[][N],int vec[N])
{
int multiply[N], i, j, row_mul_col=0;
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
{
row_mul_col=row_mul_col+vec[j]*mat[j][i];
}
multiply[i]=row_mul_col;
row_mul_col=0;
}
printf("\n The matrix after multiplication is:\n");
for(i=0;i<N;i++)
{
printf("%d\t", multiply[i]);
}
}

109
Output
 Input matrix elements of order 3*3:
2 4 6 8 1 3 5 9 7
 The matrix is:
2 4 6
8 1 3
5 9 7
 Input vector of 3 components:
2 4 1
 The 3 components vector is:
2 4 1
 The matrix after multiplication is:
26 23 53
Process: First row of the matrix [2,4,6] multiplied by the vector
[2,4,1]:
(2×2)+(4×4)+(6×1)=4+16+6=26
Second row of the matrix [8,1,3] multiplied by the vector [2,4,1:
(8×2)+(1×4)+(3×1)=16+4+3=23
similarly, others.
110
Prepared By: Rajan Kumar KC
Passing Strings to Functions
 Since strings are character arrays, the rules for passing strings to
functions are similar to those for passing arrays to functions.
 Rules
1. The string to be passed must be declared as a formal argument of
the function definition in the function header.
void display(char item_name[])
{
……………
}
2. The function prototype must show that the argument is a string.
void display(char str[]);
3. A call to the function must have a string name without subscripts
as its actual argument.
display(name);
where, name is a properly declared string in the calling function.
Note: Like arrays, strings are passed by address.

111
Questions
1. What is function? Write its advantages.
2. Define types of function with example.
3. Define different components of functions with
syntax and suitable example.
4. Write functions to add, subtract, multiply and
divide two numbers a and b.
5. Write a program to find sum of any two
numbers using function.
6. Define return statement with syntax and
example.

Prepared By: Rajan Kumar KC 112


Questions
7. Write a Program using function to find the greatest
number among three numbers.
8. Write a program to using to find the smallest number
among three numbers.
9. Define different types of functions with syntax and suitable
example.
10. Define static variable with syntax and suitable example.
11. Define register variable with syntax and suitable variable.
12. Define automatic variable with syntax and suitable
example.
13.What is recursive function? Write a program to find
factorial number of given number.
14. To become any function recursive what condition should
be there?

Prepared By: Rajan Kumar KC 113


Questions
15. Write a program to display the reverse of a number using recursion.
❖ Take a look at static variable use in recursion
16. Can we pass array to the function? Write with example.
17. Write a program to display a matrix using array and function.
18. Write a program to read a matrix of order m*n. Pass this matrix to a function which increases
each element of the matrix by 2.
19.Write a function which will take as its input a matrix of size (m*n), where m<10, n<5 and
returns the same matrix with all its elements replaced by absolute values.
20. Write a function to multiply two n*n matrices.
21. Write a function to multiply a square matrix by a vector. Assume a n*n matrix and a
n component vector. The call would give the size of the matrix and the names of the
matrix and a vector.

Note:
Vectors are a type of matrix having only one column or one row. There are two types
of vectors: column vectors and row vectors. For example, matrix a is a column
vector, and matrix a' is a row vector.
11
a= 22 a' = 11 12 33 33

Prepared By: Rajan Kumar KC 114

You might also like