You are on page 1of 21

Functions in C

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.

Why do we need functions?


 Functions help us in reducing code redundancy. If functionality is performed at
multiple places in software, then rather than writing the same code, again and
again, we create a function and call it everywhere. This also helps in
maintenance as we have to change at one place if we make future changes to
the functionality.
 Functions make code modular.
 Functions provide abstraction. For example, we can use library functions without
worrying about their internal working.

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.

Note that: You cannot imagine a C program without function.

Structure of a Function

A general form of a C function looks like this:

<return type> FunctionName (Argument1, Argument2, Argument3……)

Statement1;

Statement2;

Statement3;

return value;  return (value); or may be without return statement


(some times)

2
User defined functions can be categorized as:

o Function with no arguments and no return value


o Function with no arguments and a return value
o Function with arguments and no return value
o Function with arguments and a return value

When do we need function prototype?

Most C programmers prefer to place the main() function at the beginning


of their programs. After all, main() is always the first part of a program to be
executed. I recommend you to use this method ( First place main function then
follow all the functions after the main, and you should apply the requirement as
defined below

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.

Function prototypes are conventionally placed at the beginning of a


program (i.e., before the main() function) and are used to inform the compiler of
the name, data type, and number and data types of the arguments, of all user-
defined functions employed in the program. The general form of a function
prototype is

data-type name(type 1, type 2, ..., type n);

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:

double factorial ( int ); instead of double factorial( int n);

3
Functions with no type. The use of void

What if we want to return no value?

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.

void printmessage;//Func. prototype


void main ()
{
printmessage ();
}
void printmessage ()
{
printf("I'm a function!");
}

The Arguments

Argument1, Argument2, Argument3……are declared as:

Type1 argument1, Type2 argument 2, Type 3 argument 3, ……..an so on.

Example: int a, float b, char d, int e; and so on.

Notice that comma (,) must used to separate arguments and not semicolon (;).

Function Call:

o A function can be accessed, or called, by specifying its name, followed by


a list of arguments enclosed in parentheses and separated by commas.
Note that when you call function from main then you should not include
the type of the arguments. This mean that if your function declaration is
as follows:

int myfuncion(int A, float B) then

the call statement in main as follows (as an example):


4
C= myfuncion(A,B); or

as follows:

printf(" the value of C = %.3f\n", myfuncion(A,B));

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 ( ).

o for passing the value of an argument to a function is called passing by


value

Example:

int sum (int x, int y)

int result; /* result is local variable */

result = x + y;

return (result); /* or like: return result; */

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;

o This statement causes the value of expression to be returned to the calling


part of the program. Of course, the data type of expression should match
the declared data type of the function. For a void function, which does not
return any value, the appropriate return statement is simply: return;

o or even, don’t write the statement: return.

o A maximum of one expression can be included in a return statement. Thus,


a function can return a maximum of one value to the calling part of the
program. However, a function definition can include multiple return
statements, each containing a different expression, which is conditionally
executed, depending on the program logic.

Example:

#include "stdafx.h"

int addition (int a, int b)


{
int r;
r=a+b;
return (r);
}
int main ()
{
int z;
z = addition (5,3);
printf("The result is %d \n",z);
return 0;
}

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

2. Example program for without arguments & with return value:


In this program, no arguments are passed to the function “sum”. But, values are returned from this
function to main function. Values of the variable a and b are summed up in the function “sum” and the
sum of these value is returned to the main function.

#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) );
}

float square ( float x )


{
return x*x ;
}
Output:
Enter some number for finding square : 2
Square of the given number 2.00 is 4.00

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

Example program for C function (using call by value):

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);
}

void swap(int a, int b)


{
int tmp;
tmp = a;

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.

Example program for C function (using call by reference):


In this program, the address of the variables “m” and “n” are passed to the function “swap”. These
values are not copied to formal parameters “a” and “b” in swap function. Because, they are just holding
the address of those variables. This address is used to access and change the values of the variables.

#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);
}

void swap(int &a, int &b)


{
int tmp;
tmp = a;
a = b;
b = tmp;

Output:

values before swap m = 22 and n = 44


values after swap a = 44 and b = 22

9
Random Function

Generate random number. It returns an integer value in the range between 0 and RAND_MAX

Syntax: rand()% total number in the range + first number

a in the range 12 to 25

a = rand() % (25-12+1) + 12

Ex:

v1 = rand() % 100; // v1 in the range 0 to 99


v2 = rand() % 100 + 1; // v2 in the range 1 to 100
v3 = rand() % 30 + 1985; // v3 in the range 1985-2014

10
Eastern Mediterranean University
School of Computing and Technology
Information Technology
Lecture2 – Functions

User Defined 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;

/* calling a function to get max value */


ret = max(a, b);

printf( "Max value is : %d\n", ret );

/* function returning the max between two numbers */


int max(int num1, int num2)
{
/* local variable declaration */
int result;

if (num1 > num2)


result = num1;
else
result = num2;

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;

/* calling a function to get max value */


max(a, b);

1
}

/* function finding the max between two numbers and calling printLargest function */
void max(int num1, int num2)
{
/* local variable declaration */
int result;

if (num1 > num2)


result = num1;
else
result = num2;

printLargest(result) ;
}
//function printing largest number
void printLargest(int large)
{
printf( "Max value is : %d\n", large );
}

Example3: Program to print factorials of all integers between 0 and 5

#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));
}

Example4: Program to add numbers from 4 to 1


#include "stdafx.h"
int sum(int);
int s=0;
void main()
{

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;
}

You might also like