Lecture2 Part1
Lecture2 Part1
A function is a set of statements that take inputs, do some specific computation and
produces output.
The idea is to put some commonly or repeatedly done task together and make a
function so that instead of writing the same code again and again for different inputs,
we can call the function.
1
2
3
4
5
6
7
8
Example
9
So function in a C program has some properties as discussed below.
o Every function has a unique name. This name is used: to be called from
“main ()” function.
o A function can be called from within another function. (Function can call
another function, or even can call itself (recursive).
o Remember that a C program must has at least one function called main ().
o A function is independent and it can perform its task without intervention
from or interfering with other parts of the program.
o A function performs a specific task. A task is a distinct job that your program
must perform as a part of its overall operation, such as adding two or more
integer, sorting an array into numerical order, or calculating a cube root etc.
o A function returns a value to the calling program. This is optional and
depends upon the task your function is going to accomplish. Suppose you
want to just show few lines through function, then it is not necessary to
return a value (as an example: a function which prints string of characters
only as a heading).
o But if you are calculating area of rectangle as an example, and wanted to
use result somewhere in program, then you have to send back (return)
value to the calling function.
Structure of a Function
Statement1;
Statement2;
Statement3;
2
User defined functions can be categorized as:
In such situations, function calls [within main()] are bound to precede the
corresponding function definitions: fortunately, however, compilation errors can
be avoided by using a construct known as a function prototype.
notice that semicolon (;) must be coded as shown above in function prototype
where data-type represents the data type of the item returned by the referenced
function, name is the name of the function, and type 1, type 2,..., type n are the
data types of the arguments of the function.
Also, note that it is not necessary to specify the names of the arguments in a
function prototype. As an example: the function prototype statement for factorial
functin can be written as:
3
Functions with no type. The use of void
Imagine that we want to make a function just to show a message on the screen.
We do not need it to return any value. In this case we should use the void type
specifier for the function. This is a special specifier that indicates absence of type.
The Arguments
Notice that comma (,) must used to separate arguments and not semicolon (;).
Function Call:
as follows:
o If the function call (call statement in main) does not require any
arguments then an empty pair of parentheses must follow the name of the
function, as an example: func1 ( ).
Example:
result = x + y;
In the above: the returned value (result) is of type int, argument x is of type int,
and argument y is of type int.
Note that: x and y are integer arguments to function from main ( or from other
Functions).
Also, the argument or variable (result) is called local variable. This mean that this
variable is only known with the function (sum) defined above.
If main function or any other function called by main has also another variable
with same name as result as an example, then they are totally different and might
have different values.
void main ( )
int sum(int k,int d)
{ {int R;
R=k+d;
int x,y,v1;
return R;
}
x=40;y=70;
v1=sum(x,y);
Value of R
} 5
will be
returned to main ( )
Note that the identifiers used to reference the arguments of a function are local,
in the sense that they are not recognized outside of the function.
Return statement:
o the body of the functions must include one or more return statements in
order to return a value to the calling portion of the program.
o If the type of the function is void then function has no return statement.
o A return statement causes the program logic to return to the point in the
program from which the function was accessed. The general form of a return
statement is:
return expression;
Example:
#include "stdafx.h"
6
1. Example program for without arguments & without return value:
In this program, no values are passed to the function “test” and no values are returned from this
function to main function.
#include "stdafx.h"
void test();
void main()
{
test();
}
void test()
{
int a = 50, b = 80;
printf("\nvalues : \na = %d and b = %d\n\n", a, b);
}
Output:
values :
a = 50 and b = 80
#include "stdafx.h"
int sum();
void main()
{
int addition;
addition = sum();
printf("\nSum of two given values = %d\n\n", addition);
}
int sum()
{
int a = 50, b = 80;
return a+b;
}
Output:
Sum of two given values = 130
7
3. Example program for with arguments & with return value:
The value of “m” is passed as argument to the function “square”. This value is multiplied by itself in
this function and multiplied value “p” is returned to main function from function “square”.
#include "stdafx.h"
float square ( float x );
void main( )
{
float m ;
printf ( "\nEnter some number for finding square : ");
scanf ( "%f", &m ) ;
printf ( "\nSquare of the given number %.2f is
%.2f\n\n",m,square(m) );
}
4. Call by value:
In call by value method, the value of the variable is passed to the function as parameter.
The value of the actual parameter can not be modified by formal parameter.
Different Memory is allocated for both actual and formal parameters. Because, value of actual
parameter is copied to formal parameter.
Note:
Actual parameter – This is the argument which is used in function call.
Formal parameter – This is the argument which is used in function definition
In this program, the values of the variables “m” and “n” are passed to the function “swap”.
These values are copied to formal parameters “a” and “b” in swap function and used.
#include "stdafx.h"
void swap(int a, int b);
void main()
{
int m = 22, n = 44;
printf("\nvalues before swap m = %d nand n = %d\n", m, n);
swap(m, n);
}
8
a = b;
b = tmp;
printf("\nvalues after swap m = %d and n = %d\n\n", a, b);
}
Output:
values before swap m = 22 and n = 44
values after swap m = 44 and n = 22
5. Call by reference:
In call by reference method, the address of the variable is passed to the function as parameter.
The value of the actual parameter can be modified by formal parameter.
Same memory is used for both actual and formal parameters since only address is used by both
parameters.
#include "stdafx.h"
void swap(int &a, int &b);
void main()
{
int m = 22, n = 44;
printf("\nvalues before swap m = %d and n = %d\n",m,n);
swap(m, n);
printf("\nvalues after swap a = %d nand b = %d\n\n",m,n);
}
Output:
9
Random Function
Generate random number. It returns an integer value in the range between 0 and RAND_MAX
a in the range 12 to 25
a = rand() % (25-12+1) + 12
Ex:
10
Eastern Mediterranean University
School of Computing and Technology
Information Technology
Lecture2 – Functions
Example1:
#include "stdafx.h"
/* function declaration */
int max(int num1, int num2);
void main ()
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
return result;
}
Example2:
#include "stdafx.h"
/* function declaration */
void max(int num1, int num2);
void printLargest(int);
void main ()
{
/* local variable definition */
int a = 100;
int b = 200;
1
}
/* function finding the max between two numbers and calling printLargest function */
void max(int num1, int num2)
{
/* local variable declaration */
int result;
printLargest(result) ;
}
//function printing largest number
void printLargest(int large)
{
printf( "Max value is : %d\n", large );
}
#include "stdafx.h"
#include "stdlib.h"
double factorial(int n)
{
/*Function to evaluate factorial (in floating-point form)
of non-negative integer n. */
int count;
double fact = 1.;
/* Abort if n is negative integer */
if (n < 0)
{
printf("\nError: factorial of negative integer not defined\n");
exit(1);
}
/* Calculate factorial */
for (count = n; count > 0; --count)
fact *= (double) count;
/* Return value of factorial */
return fact;
}
void main()
{
int j;
/* Print factorials of all integers between 0 and 20 */
for (j = 0; j <= 5; ++j)
printf( "factorial(%d) = %.2f\n", j,factorial(j));
}
for(int i=4;i>0;i--)
s=sum(i);
printf("Sum of numbers from 4 - 1 : %d\n",s);
}
2
int sum(int a)
{
s=s+a;
return s;
//or
//return s+a;
}