Sie sind auf Seite 1von 51

Functions

Functions

Return_ type function_name(arglist)


{
//local variable declaration
// statements
//return statement
}
Return_ type function_name(arglist)
{
//local variable declaration
// statements
//return statement
}

10 20
Sum=30
Functions
Why functions
Program that we study from textbooks to learn c language
are very small when compared to real world business
problems, if the program is very big, there are some
disadvantages
1. Very difficulty to understand the big program without
modules
2. It is very difficulty for the programmer to write large
programs
3. Is it difficulty to identify the logical error and debug
4. Large programs are more prone to errors
These disadvantages can be overcome using functions.
Functions:
Example:

What is function? int Add(int x,int y)


“Set of instructions to perform a {
specific task”
int z; //local variable declaration
Ex: 1. To find area of circle
2. To add two numbers z=x+y; // statements
3. To find simple interest reurn z; //return statement
4. sorting numbers }

Function definition
Return_ type function_name(arglist) Calling a function
{ By using function name
//local variable declaration Ex Add(10,20);
// statements
//return statement
}
Write a program to find area of circle using Write a program to add two numbers
functions using functions
#include<stdio.h>
#include<stdio.h>
float findarea(int r);
int add(int x,int y);

void main() void main()


{ {
float area; int a,b,sum;
printf(“enter two numbers”);
area=findarea(10);
Scanf(“%d%d”,&a,&b);
printf(“ area is %d”, area); sum=Add(a,b);
} printf(“sum is %d”,sum);
float findarea(int r) }
{ int Add(int x,int y)
{
float a; //local variable declaration
int z; //local variable declaration
a=3.14*r*r; // statements
z=x+y; // statements
return (a);
reurn z; //return statement
} }
Advantages of functions
Reusability: code can be reused number of times.

Less space: functions reduce the length of the program and


thereby program takes less space.

Debugging is easy.

Program readability increases.

Program becomes more understandable.

Complex Program can be divided into modules.


Write a program using functions to convert
given temperature from Celsius to Fahrenheit
Celsius to Fahrenheit:
To convert temperatures in degrees Celsius to Fahrenheit, multiply by 1.8 (or 9/5)
and add 32.
Example: 30°C x 1.8 + 32 = 86°F
Functions:
Example:

What is function? int Add(int x,int y)


“Set of instructions to perform a {
specific task”
int z; //local variable declaration
Ex: 1. To find area of circle
2. To add two numbers z=x+y; // statements
3. To find simple interest reurn z; //return statement
4. sorting numbers }

Function definition
Return_ type function_name(arglist) Calling a function
{ By using function name
//local variable declaration Ex Add(10,20);
// statements
//return statement
}
To add two numbers using functions
#include<stdio.h>
int add(int x,int y);
void main() a??? b??? sum??
{
int a,b,sum;
printf(“enter two numbers”); a=10 b=20 sum??
Sum=
scanf(“%d%d”&a,&b);
sum=Add(a,b); 30
printf(“sum is %d”,sum);
}
int Add(int x,int y)
{
int z; //local variable declaration X=10 Y=20
z=x+y; // statements
reurn z; //return statement
} z???
Z=30
Total space =2+2+2
2+2+2 bytes
Elements of User Defined Functions(UDF)
 Function definition
 Function call
 Function declaration
program using functions with all elements indicated(adding two numbers)
include<iostream>
using namespace std ?????
int add(int x,int y); function declaration
void main()
{
int a,b;
printf(“enter two numbers”);scanf(“”%d%d”,&a,&b);
sum=add(a,b); ?????
Printf(“sum is %d”,sum) function call(caller)
}
int add(int x,int y)
{
int z;z=x+y; ??????????
return z; function definition(cally)
}
Types of functions:
Built-in/Library functions
Ex: sqrt(),pow(),log()…. Etc
User defined functions
Ex: Add(), max(a,b)

There are 4 types of user defined functions


 Functions with no parameters and no return values

 Functions with no parameters and return values

 Functions with parameters and no return values

 Functions with parameters and return values


1) Functions with no parameters and no return values
#include <stdio.h>
void add();
int main(void)
{
int main() TestFunct();
{
...
add();
} }

void add()
{ void TestFunct(void)
int a,b,sum;
{
printf(“Enter the values for a & b\n”);
scanf(“%d %d, &a, &b); // receive nothing
// and nothing to be
sum= a+b;
// returned
printf(“%d”, sum); }
}
2) Functions with no parameters and return values
#include <stdio.h>
void add(); void main(void)
{
int main() x = TestFunct();
{ ...
int sum;
}
sum=add();
printf(“sum is %d”,sum)
}
int TestFunct(void)
int add() {
{ // received nothing
int a,b,sum;
//but need to
printf(“Enter the values for a & b\n”);
scanf(“%d %d, &a, &b); // return something
return 123;
sum= a+b;
}
return sum
} Hey Add any two numbers and give me result
3) Functions with parameters and no return values
#include <stdio.h>
void add(int x,int y) void main(void)
{
int main() x = TestFunct();
{ ...
int a,b,sum;
}
cout<<“enter two numbers”;
scanf(“%d%d”,&a,&b);
sum=Add(a,b);
} void TestFunct(int x,…. …)
{
void add(int x,int y) // receive something
{ //but need not
int z; // return anything
z=x+y;
printf(“sum is %d”,z);
}
}

Hey Add these two numbers(a&b) and don't give me result


4) Functions with parameters and return values
#include <stdio.h>
int add(int x,int y)
void main(void)
int main() {
{ x = TestFunct(…..);
int a,b,sum;
...
cout<<“enter two numbers”;
scanf(“%d%d”,&a,&b); }
sum=Add(a,b);
printf(“the sum is”,sum)
} int TestFunct(int x….. …)
{
int add(int x,int y) // receive something
{ // and need to return
int z;
//something
z=x+y;
return z return 123;
} }
Return statement
There are three forms of return statement, they are
 Simple return

 return with value or return with exp

 multiple return statements

Simple return statement


Example:
void add()
{
……
……
return //simple return statement, that returns the control
}
return statement with value or expression
Example:
int Add(int x,int y)
{
int z; //local variable declaration
z=x+y; // statements
reurn z; //return statement with value of z
}
Multiple return statements: more than one return statements in a function
Example:
int max(int x,int y)
{
if(x>y)
return x;
else
return y;
}
Write alg and program to find factorial of a number using functions.
Alg: To find factorial of a number using functions.
Step1: read a number.
Read n
Step2: call the function to find factorial
f=fact(n)
Step3: print f
Step 4: stop

Function fact(n)
Step1:f=1
Step2: find factorial
for(i=1;i<=n;i++)
f=f*i
end for
Step 3: return f
1.Read the range n1 & n2
2. Generate prime numbers between n1& n2
for(i=n1; i<=n2; i++)
k=prime(i)
if(k==1)
print i;
end for
3.stop
Function isprime(n)
1. for(i=2;i<n;i++)
if(n%i==0)
return0
end if
return 1
end for
B
start

Isprime(n)
Read n1, n2

For(i=2;i<n;i++)
for i=n1; i<n2; i++ F
T

n%i=
A Isprime(i) B
0?

F K==1? Return 0 Return 1


T

Print “i”
A

stop
Actual parameters and Formal parameters
Actual parameters: parameters present in the function call
Ex:
sum=Add(a,b); //here a and b are actual parameters

Formal parameters: parameters present in the function definition


Ex:
// here x and y are formal parameters

int Add(int x,int y)


{

}
Note:
The number of actual parameters should be equal to number of
formal parameters( both number and type should match)
Scope of variables in functions
#include <stdio.h>
int add(int x,int y);
a,b ,sum are
local to main
int main()
{
int a,b,sum;
cout<<“enter two numbers”;
scanf(“%d%d”,&a,&b);
sum=Add(a,b);
printf(“the sum is”,sum)
}

int add(int x,int y)


{
int z;
x,y,z are local
z=x+y; to add
return z
}
Passing parameters to functions
Pass by value
Pass by reference
Write prgm to show pass by value and pass by ref
Example :By value Example: By reference
int main() int main()
{ {
int a=10,b=20; int a=10,b=20;
printf(“before swap %d%d”,a,b); printf(“before swap %d%d”,a,b);
swap(a,b); swap(&a,&b);
printf(“after swap %d%d”,a,b); printf(“after swap %d%d”,a,b);
} }
void swap(int x,int y) void swap(int x*,int *y)
{ {
int temp; int temp;
temp=x; temp=*x;
x=y; *x=*y;
y=temp; *y=temp;
} }
Actual parameters and Formal parameters
Actual parameters: parameters present in the function call
Ex:
sum=Add(a,b); //here a and b are actual parameters
Formal parameters: parameters present in the function definition
Ex:
int Add(int x,int y) // here x and y are formal parameters
{
......................
}

Note:
The number of actual parameters should be equal to number of
formal parameters( both number and type should match)
Passing parameters to functions
Pass by value
Pass by reference
Write prgm to show pass by value and pass by ref
Example: By value Example: By reference
int add(int x,int y); void swap(int *x,int *y);
void main() int main()
{
{
int a=10,b=20;
int a,b,sum;
printf(“before swap %d%d”,a,b);
printf(“enter two numbers”); swap(&a,&b);
scanf(“%d%d”,&a,&b); printf(“after swap %d%d”,a,b);
sum=Add(a,b); }
printf(“sum is %d”,sum); void swap(int x*,int *y)
} {
int Add(int x,int y) int temp;
{ temp=*x;
*x=*y;
return(x+y);
*y=temp;
}
}
Main boss says, take these values and swap them, give me swapped values
Passing parameter to functions
int main() int main()
{ {
int a=10,b=20; sender(10,20);
sender(a,b); }
}
Receiver(int x,int y)
Receiver(int x, int y) { int main()
{ --------------- {
----------- } int a=10,b=20;
}
sender(&a,&b);
}
int main() int main()
Receiver(int *x,int *y)
{ int a=10,b=20; {
{
sender(a+2,b+3); int a=10; float b=20.5;
--------------------
} sender(a,b);
}
}
Receiver(int x,int y) Receiver(int x,float y)
{ {
---------------
--------------------
}
}
passing arrays to functions
Just pass the base address of the array to a function

int main() int main() int main()


{ {
int a[7]={1,2,3} {
int a[7]={1,2,3,4,5,6,7} int a[7]={1,2,3,4,5}
sender(a); int item=4; printf("%d\n",a);
} ------------ printf("%d\n",a[0]);
Receiver(int x[7]) found=linSearch(a,item,n); printf("%d\n",*a);
{ --------------------
}
} printf("%d\n",*(a+1));
linSearch( int x[],int k,int n) }
{
------------------
}
Difference between actual and formal parameters
Actual parameters formal parameters
they are used in calling function These are used in function header of called
Ex function
Sum=Add( a,b); Ex
Here a,b are actual parameters int Add(int x,int y)
{
}
// here x and y are formal parameters
Actual parameters can be constants, variables or Formal parameters should only be variables
expressions ex
Ex int Add(int x,int y)
Sum=Add(a,b);//variables {
Sum=Add(10,20)//constants }
Sum=Add(a+4,b);//expressions
They send values (to formal parameters) They receive values (from actual parameters)
Address of actual parameters can be sent (to Pointers will receive the address (from actual
formal parameters) parameters)
2D ARRAYS:
Elements are stored in the form of matrix (rows & columns).

Declaration :
data_type arr_name[rowsize][columnsize]
ex: int a[2][2]; int a[2][2]={ {1,2},
int matrix[3][3];
{3,4}
int a[2][2]={ {1,2}, {3,4} };
};
int a[2][2]={ {1,2}, {3,4} };
0,0 0,1 rows
1 2
1 2
a[0][0] a[0][1]
3 4
1,0 1,1
3 4
Column a[1][0] a[1][1]

i= row
j=column
In general to access any particular element
a[i][j]
Using 2-dimensional arrays:
Reading 2D arrays Printing 2D arrays
printf("entr the order of matrix");
printf(“matrix elements”);
scanf("%d%d",&m,&n);
printf("enter matrix A"); for(i=0; i<m; i++)
for(i=0;i<m;i++) {
{
for(j=0; j<n; j++)
for(j=0;j<n;j++)
{ {
scanf("%d",&a[i][j]); printf(“%d”, a[i][j]);
} }
}
}
Manipulation of 2-dimensional arrays:

 Addition of two matrices and store the result in c.

 Subtract a matrix from other matrix and store the result in c.

 Sum of elements of a given matrix.

 Average of all the elements of a given matrix.

 Largest element in a given matrix.

 Transpose of a matrix.

 Trace of a matrix.
WAP to find sum of all elements in a matrix

1.Read the order of matrix m,n

2.Read mxn elements using for loops

3.Find the sum of all elements using for loops

sum =sum+a[i][j];
Using functions to find sum of all elements in a
matrix
......................
int main()
{
int a[10][10],m,n;

printf("enter the order of matrix");


scanf("%d%d",&m,&n);
readmatrix(a,m,n);

findsum(a,m,n);
}
void readmatrix(int a[10][10],int m,int n)
{
int i,j;
printf("enter matrix elements");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
}
Function to find sum of all elements in a matrix
void findsum(int a[10][10],int m, int n)
{
int sum=0,i,j;
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
sum=sum+a[i][j];
}
}
printf("the sum is %d",sum);
}
int main() }
{
int a[10][10],b[10][10],c[10][10];
int i,j,m,n; for(i=0;i<m;i++)
printf("entr the order of matrix"); {
scanf("%d%d",&m,&n); for(j=0;j<n;j++)
printf("enter matrix A"); {
for(i=0;i<m;i++) c[i][j]=a[i][j]+b[i][j];
{ }
for(j=0;j<n;j++) }
{ printf("sum of matrix A and B is ");
scanf("%d",&a[i][j]); for(i=0;i<m;i++)
} {
} for(j=0;j<n;j++)
printf("enter matrix B"); {
for(i=0;i<m;i++) printf("%d",c[i][j]);
{ }
for(j=0;j<n;j++) }
{ return 0;
scanf("%d",&b[i][j]); }
} Matrix Addition
Add 2 matrices and store the result in c using functions
int main()
{
int a[10][10],b[10][10],c[10][10]; int m,n,p,q;
printf("entr the order of matrix A");
scanf("%d%d",&m,&n); Read matrix a of
readmatrix(a,m,n); order mxn

printf("entr the order of matrix B"); Read matrix b of


scanf("%d%d",&p,&q); order mxn
readmatrix(b,p,q);

addmatrix(a,b,c,m,n); Add matrix a& b store result


in c of order mxn
printmatrix(c,m,n);
Print matrix c of
order mxn
}
void readmatrix(int a[10][10],int m,int n)
{
int i,j;
printf("enter matrix elements");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
}
void addmatrix(int a[10][10],int b[10][10],int c[10][10],int m, int n)
{

int sum=0,i,j;
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}

}
void printmatrix(int c[10][10],int m,int n)
{
int i,j;
printf("sum of matrix A and B is ");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d",c[i][j]);
}
}

}
WAP using functions to find trace of a matrix

Trace of a matrix :
Matrix A of size 3x3

10 15 20
Trace
25 30 35
10+30+50 = 90
40 45 50
We can write the following steps:
Initial : sum = 0
Step 1: sum = sum + a[0][0]
Step 2: sum = sum + a[1][1]
Step 3: sum = sum + a[2][2]
.................................................
.................................................
Step n: sum = sum + a[n-1][n-1]
In general,
sum = sum + a[i][i] where i=0,1,2,3......n-1
So, we are forced to use the for statement:
to find the trace of a matrix.

sum=0
for(i=0; i<n; i++)
{
sum=sum+a[i][i];
}

-------------------------
WAP using functions to find product of 2 matrices

Home work
type

Function Header name

parameters
Function
Definition Declaration
statements

Function Body Executable


statements

return statements
C FUNCTIONS
Do not pass argument Do pass arguments
void main(void) void main(void)
{ {
TestFunct(); TestFunct(123);
... ...
} }

void TestFunct(void) void TestFunct(int i)


No return
{ {
// receive nothing // receive something and
// and nothing to be // the received/passed
// returned // value just
} // used here. Nothing
// to be returned.
}
void main(void) void main(void)
{ {
x = TestFunct(); x = TestFunct(123);
... ...
} }

With a return int TestFunct(void) int TestFunct(int x)


{ {
// received/passed // received/passed something
// nothing but need to // and need to return something
// return something return (x + x);
return 123; }
}

www.tenouk.com, © 65/66
Functions
Manager

Team Lead1 Team Lead2

Programmer
Programmer 1 Programmer 3
2

Das könnte Ihnen auch gefallen