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

Functions

A function groups statements together and gives them a name. Functions optionally return a value. Functions have a return type, name, and parameter list. Parameters must be declared with both type and name. Variables within functions are local and destroyed after the function exits. Arguments passed to functions can be passed by value or reference. Passing by reference allows changing the original argument. Functions must be declared before use with a prototype. Arrays can be passed to functions where the array name represents the base address.

Uploaded by

osama.20en714
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Functions

A function groups statements together and gives them a name. Functions optionally return a value. Functions have a return type, name, and parameter list. Parameters must be declared with both type and name. Variables within functions are local and destroyed after the function exits. Arguments passed to functions can be passed by value or reference. Passing by reference allows changing the original argument. Functions must be declared before use with a prototype. Arrays can be passed to functions where the array name represents the base address.

Uploaded by

osama.20en714
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Function

A function groups a number of program statements into a unit and gives it a


name. This unit can then be invoked from other parts of the program. It also
optionally returns a value to the calling program.
The General Form of a Function
ret-type function-name(parameter list)
{
body of the function
}
• The ret-type specifies the type of data that the function returns. A function
may return any type of data(int, float, double, char) except an array.
• The parameter list is a comma-separated list of variable names and their
associated types. A function may be without parameters, in which case the
parameter list is empty.
all function parameters must be declared individually, each including both the
type and name. For example, here are correct and incorrect function parameter
declarations:
f(int i, int k, int j) /* correct */
f(int i, k, float j) /* incorrect */
Lec. Sahar Khalid
int sum (int x, int y)
{
int result; Formal
result = x + y; parameter
return (result);
}
Variables that are defined within a function are called local variables. A local variable
comes into existence when the function is entered and is destroyed upon exit. That is,
local variables cannot hold their value between function calls.
Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function. They behave
like other local variables inside the function and are created upon entry into the function
and destroyed upon exit. As shown in the above function, the parameter declarations
occur after the function name. The function sum has two parameter x,and y.

Call by Value, Call by Reference


In a computer language, there are two ways that arguments can be passed to a
subroutine.
1. call by value.
2. Call by reference.
Lec. Sahar Khalid
Function Prototypes
In C++ all functions must be declared before they are used. This is
normally accomplished using a function prototype.
The general form of a function prototype is
type func_name(type parm_name1, type parm_name2,. . .,type parm_nameN);

#include <iostream> #include <iostream>


using namespace std; using namespace std;
void ff(int a, int b) void ff(int a, int b); //function declaration
{ //prototype
cout<< a % b; int main(void)
} {
int main(void) ff(10,3); /*calling function*/
{ return 0;
ff(10,3); }
return 0; void ff(int a, int b) /*Definition*/
} {
In this example, since ff( ) is defined cout<< a % b;
prior to its use in main( ), no separate }
prototype is required. In this example, prototype is required.
Lec. Sahar Khalid
Call By Value
This method copies the value of an argument into the formal parameter of
the function. In this case, changes made to the parameter have no effect on
the argument. By default, C/C++ uses call by value to pass arguments.
#include <iostream>
using namespace std;
int sqr(int x); //prototype(declaration) of the function
int main(void)
{
the value of the argument to sqr( ), 10, is
int t=10;
copied into the parameter x. When the
cout<<sqr(t)<< t; assignment x = x*x takes place, only the local
return 0; variable x is modified. The variable t, used to
} call sqr( ), still has the value 10. Hence,
argument
int sqr(int x )
{
the output is
x = x*x; parameter
100 10.
return(x);
}
Lec. Sahar Khalid
The return Statement
The return statement has two important work
1. First, it causes an immediate exit from the function that it is in. That
is, it causes program execution to return to the calling code.
2. Second, it may be used to return a value.
Functions of Type void
One of void's uses is to explicitly declare functions that do not return
values. For example, the pr_maxno( ) function in this program simply
prints maximum between two numbers on the screen.
#include <iostream> void pr_maxno(int x,int y)
using namespace std; {
void pr_maxno(int x,inty); //declaration if(x>y)
int main(void) cout<<x;
else if(y>x)
{ int x,y; cout<<y;
cout<<“enter two numbers”; else
cin>>x>>y; cout<<“equal”;
}
pr_maxno(x, y);
return 0;
Lec. Sahar Khalid
}
A function can contain multiple return statements, only one return
statement is executed because it terminate the function execution. For
example: function return 1 if parameter is even ,and 0 if parameter is odd
#include <iostream>
using namespace std;
int check_even(int a)
{
if(a%2==0)
return 1;
return 0;
}
int main()
{
int n,result;
cout<<"enter your number";
cin>>n;
result=check_even(n);
if(result)
cout<<"even";
else
cout<<"odd";
Lec. Sahar Khalid
}
#include <iostream>
Write a program with a function named maxno with
using namespace std;
two integer parameter, this function return the
int maxno(int x,int y)
maximum number. Use this function in the main()
{
function to find the maximum number from 10
if(x>y)
numbers.
return x;
else
return y;
}

int main()
{ int i,maxv,x;
cout<<"input ten integer numbers";
cin>>maxv;
for(i=1;i<10;i++)
{
cin>>x;
maxv=maxno(maxv,x);
}
cout << "maximum value=" <<maxv<< endl;
return 0;
} Lec. Sahar Khalid
Call by Reference
Passing arguments by reference uses a different mechanism. Instead of a value
being passed to the function, a reference to the original variable, in the calling
program, is passed. (It’s actually the memory address of the variable that is
passed). this provides a mechanism for passing more than one value from
the function back to the calling program.

Reference parameters are indicated by the ampersand (&) following the data
type:
The function declaration echoes the usage of the ampersand in the definition:
void intfrac(float, float&, float&); // ampersands in prototype

The ampersand is not used in the function call:


intfrac(number, intpart, fracpart); // no ampersands

While intpart and fracpart are passed by reference, the variable number is
passed by value.

Lec. Sahar Khalid


The next example, The main() part of this program asks the user to enter a number of type
float. The program will separate this number into an integer and a fractional part. The
intfrac() function finds the integer part and the fractional part.
#include <iostream>
using namespace std;
int main()
{
void intfrac(float, int&, float&); //declaration
int intpart;
float number, fracpart; //float variables
cout << "\nEnter a real number: "; //number from user
cin >> number;
intfrac(number, intpart, fracpart); //find int and frac
cout << "Integer part is " << intpart << ", fraction part is " << fracpart << endl;
return 0;
}
// finds integer and fractional parts of real number
void intfrac(float n, int& intp, float& fracp)
{
intp = n; Note:intp and intpart are different names for the
fracp = n - intp; //subtract integer part same place in memory, as are fracp and fracpart.
}
Lec. Sahar Khalid
Example:
the function swap( ), which exchanges the values of the two integer numbers passed to it
by reference.
#include <iostream>
using namespace std;
int main()
{
void swap(int&, int&); //prototype
int n1=99, n2=11;
swap(n1, n2);
cout << “n1=” << n1 << endl;
cout << “n2=” << n2 << endl;
return 0;
}
void swap(int& numb1, int& numb2)
{
int temp = numb1; //swap them
numb1 = numb2;
numb2 = temp;
}

Lec. Sahar Khalid


Passing Arrays to Functions
Arrays can be used as arguments to functions.

1-Passing Single-Dimension Arrays to Functions


When the function is called, only the name of the array is used as an argument.
func1(i); // function call
This name ( i in this case) actually represents the memory address of the array i
main(void)
{
int i[10];
func1(i);.
.
}
Function Definition with Array parameters

1-sized array 2-unsized array


void func1(int x[10]) void func1(int x[])
{ {
. .
. .
. .
} } Lec. Sahar Khalid
#include <iostream>
using namespace std; This example contains two functions the
int maxarr (int , int [ ]); //prototype first finds the maximum element in the
void readarr(int len,int a[ ]); //prototype array , and the second reads the array.
int main ( ) The two functions have two parameters,
{ int a[10],i,j,max; the first represents the array length, and
readarr(10,a); the second represents the array address.
max=maxarr(10,a);
cout<<"maximum element in the array="<<max;
}
int maxarr(int len , int a[ ])
{
int k,max;
max=a[0];
for (k = 0 ; k < len ; k++)
if(a[k]>max)
max=a[k];
return max;
}
void readarr(int len , int a[ ])
{
int k ;
for (k = 0 ; k < len ; k++)
cin>>a[k] ; Lec. Sahar Khalid
}
2-Passing two dimensional array to function
#include <stdio.h>
void printarray (int [ ][7], int);
int main( )
{
int calendar[5][7],i,j;
.
.
.
printarray (calendar , 5);
}
// two methods for defining a two dimensional array
//as a function parameter
void printarray (int cal[ ][7], int j) // or void printarray (int cal[5][7])
{
int k, n ;
for (k = 0 ; k < j ; k++)
{
printf ("\n");
for (n = 0 ; n < 7 ; n++)
printf ("%3d ", cal[k][n]);
} Lec. Sahar Khalid
}
#include<stdio.h> Write a program to find the value of the following
#include<string.h> expression
W=(A+B)
void read2d(int a[4][4]) Where A ,B ,and W are two dimensional arrays of size 4*4
{int i,j;
for(i=0;i<4;i++) main()
for(j=0;j<4;j++) {
Scanf("%d",&a[i][j]); int A[4][4],B[4][4],W[4][4];
} read2d(A); read2d(B);
void print2d(int a[ ][4], int ad) add2d(A,B,W);
{int i,j; print2d(W,4);
for(i=0;i<ad;i++) }
{printf("\n");
for(j=0;j<4;j++)
printf("%d",a[i][j]);
}}
void add2d(int a[4][4],int b[4][4],int
z[4][4])
{int i,j;
for(i=0;i<4;i++)
for(j=0;j<4;j++)
z[i][j]=a[i][j]+b[i][j];
} Lec. Sahar Khalid

You might also like