Unit 7 Functions
Unit 7 Functions
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
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.
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
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.
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);
}
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;
}
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);
}
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
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.
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?
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);
}
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
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
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
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]);
}
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
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]);
}
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]);
}
104
Output
Input first matrix elements of order 3*3:
2 4 6 8 1 3 9 3 5
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]);
}
107
printf("Input vector of %d components:\n", N);
for(i=0;i<N;i++)
scanf("%d", &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.
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