University of Asia Pacific (UAP)
Department of Electrical & Electronic Engineering (EEE)
Course Code: EEE 106
Course Title: Computer Programming Sessional
Lab Sheet: 07
FUNCTIONS IN C
Learning Outcomes:
Upon completion of this Lab, the students will be able to:
construct programs modularly from small pieces called functions.
create new functions.
use the mechanisms that pass information between functions.
learn how the function call/return mechanism is supported
Outlines:
Lab Task 7(a) :A theoretical overview
Lab Task 7(b): Programming Examples
Lab Task 7(c): Code Analyzer
Lab Task 7(d): In Lab Evaluation
Homework
Lab Task 7(a): A theoretical overview
A. Function Definition:
A function is a self-contained subprogram which is meant to do some specific ,wel-defined task .A
C program consists of one or more [Link] a program consists of only one function, it must be
the main( ) function.
A function definition is the actual function. The definition contains the code that will be executed. The first
line of a function definition, called the FUNCTION HEADER, should be identical to the function prototype, with
the exception of the semicolon. A function header shouldn't end with a semicolon. In addition, although the
argument variable names are optional in the prototype, they must be included in the function header.
Following the header is the function body, containing the statements that the function will perform. The
function body should start with an opening bracket and end with a closing bracket. If the function return type
is anything other than void, a return statement should be included, returning a value matching the return type.
For example, we have used the printf() function in almost every sample program . Each time, we had to
include a header file <stdio.h>, because the header file contains the declaration of printf(), which indicates to
the compiler the return type and prototype of the function. The definition of the printf() function is placed
somewhere else. In C, the definition of this function is saved in a library file that is invoked during the linking
states.
Note: For a library function, the corresponding header file contains the definition, whereas for a
programmer defined function ,the programmer himself should write the function definition.
Prepared By: Dr. Tishna Sabrina, Asst. Professor EEE, UAP
Farhana Akter Mou, Lecturer
B. Parts of a function definition:
Every function has a header and a body. A function is defined by giving its header and body.
A function header:
A function's header consists of -
i)The data type returned, or the keyword void when the function does not return a value.
ii)The function's name.
iii)In parentheses, a list of parameters and their types separated by commas, or the keyword void if the
function has no parameters.
The returned data type is optional; if it is omitted, it defaults to int. The right parenthesis that terminates the
parameter list is not followed by semicolon. There is no limit to the number of parameters a function can have,
except that the number of parameters must be the same as the number of arguments in any invocation of the
function.
The body
The header is followed by the body . A function's body consists of a group of statements enclosed in a pair of
braces.
A user defined function with its body:
int sum(int x,int y)
{
int result;
result = x+y;
return result;
}
Every program must contain one function name where the program begins execution. The main function
may call other functions, which in turn still can call other function. When a function is called, program
execution is transferred to the first statement in the called function. The function is completed when it
executes the last statement in the function or it executes a return statement. After a function returns to the
calling function, execution continues with the evaluation of the expression in which the call made. A value can
be returned when a function completes, and that returned value can be used as an operand in an expression. If
the returned value is not assigned or used, then it is simply discarded.
C. Function Declaration:
A function's declaration is different form definition. To define a function is to create it by giving its
header and its body. To declare a function is to give the data of the value that the function returns ( or void if
the function does not return a value), its name, and in parentheses the data type of its parameter the data type
of the parameters separated by commas (or void if the has no parameters).
Unlike a function definition, a function declaration is terminated by a semicolon. The standard style of writing
function declarations in which the data types are included within parentheses is called function prototype
form.
Prepared By: Dr. Tishna Sabrina, Asst. Professor EEE, UAP
Farhana Akter Mou, Lecturer
D. Declaration versus Definition:
According to the ANSI standard, the declaration of a variable or function specifies the interpretation and
attributes of a set of identifiers. The definition, on the other hand, requires the C compiler to reserve storage
for a variable or function named by an identifier.
A variable declaration is a definition, but a function declaration is not. A function declaration alludes to a
function that is defined elsewhere and specifies what kind of value is returned by the function. A function
definition defines what the function does, as well as gives the number and type of arguments passed to the
function.
A function declaration is not a function definition. If a function definition is placed in your source file before
the function is first called, you don't need to make the function declaration. Otherwise, the declaration of a
function must be made before the function is invoked.
E. Function Prototypes:
In C it has always been required that you declare a function for the compiler if it returned a data type other
than integer, but the parameter did not have to be described. In ANSI C, to maximize error checking by the
compiler, prototypes were developed. Prototypes are placed at the front of your programs to describe the
functions you are calling with their parameters.
F. About the return Statement:
a) If a C program is very simple, it may consist of just one function, main(); but usually invokes other
function, some of which invoke others.
b) A function always returns to its invoker/caller function. When a function is invoked, the statement in
its body begin executing and continue until either a return statement or the last statement in its body is
executed, after which the statements in the invoking function resume execution in their regular
sequence.
c) The return statement is optional in a function that does not return a value
but, if used, it is written
return ;
d) If a function that does not return a value contains no return statement, the function returns to its
invoker after the last statement in the function's body is executed.
e) A function that return a value must have at least one return statement,
which is written
1. return (exprn) ;
or
2. return exprn ;
where exprn is any legal C expression. The two forms have exactly the same meaning. When either is
executed, the function return the value exprn to its invoker. A function can return at most one value
per invocation.
f) A function may contain any number of return statements. Of course, only one return statement is
executed per invocation, because the return statement returns control, and perhaps a value, to the
invoking function.
g) As a rule of thumb, we suggest keeping the number of return statements small, otherwise, functions
become hard to understand, hard to debug and hard to look after.
h) A function can return only a single value each time it is called. As soon as a return statement is
executed, the function terminates, so following this statement with any other statements (including
other returns) is meaningless.
i) An exception to this rule is when the return ends one clause of an if statement. In this case, the other
may include alternate statements, including another return. For example :
if ( a< 7) return (a) ;
else a++;
Prepared By: Dr. Tishna Sabrina, Asst. Professor EEE, UAP
Farhana Akter Mou, Lecturer
j) It is also permissible to use the return statement to force termination of a function that returns no
value, as in the following example :
if ( i = = 0) return ;
which returns control to the calling program if i equals to zero.
G. Function Declaration for Returning Data Type other than int:
The C compiler assumes that if a function returns a value, it is an integer value. If it returns other type, the
function must be declared before it is referenced so the compiler is informed what kind of data is expected.
The declaration of function returning a data type other than int is usually made after the #include statements
and before the function name.
H. void Return Type
If a function does not return a value, then the function is said to return a null, or void value. To make this
obvious, the word void is used as the return data type in the function source code and in documentation
describing. This lets the user know that the function does not return a value.
The compiler can use a function declaration to check for matches between arguments and parameters of
functions and issue appropriate warning and error messages if it detects problems.
I. Function Arguments:
Functions are effective in C because they provide good two-way communications between the calling function
and the called function. When a function is called in C, data arguments pass to the called functions. The data
arguments passed are a copy of the data in the calling function so the called function can change it and not
destroy the original data in the calling function. When the called function completes, it may return a value to
the calling function. The default data that a function returns is int type, but any of the basic data types can be
returned.
If no arguments are needed by a function, the function name is followed by an empty argument list. ( ).
Otherwise, the argument list specifies a name for each argument, which the function uses to reference the
particular argument. All the data types of the arguments are declared immediately following the function list.
If a data type is not declared, then the data type is assumed to be int (integer). A good programming practice is
to always specify the argument's data type.
If no value is to be returned by the function, then the word void is used in front of the function name
when defined to specify that there is no return value.
J. Matching Parameters with Arguments
Although arguments and parameters may have different names, a function's parameters should match the
function's arguments in number and data type. For example, if a function is invoked with two arguments, it
should have two parameters. If the arguments are of type int and char, respectively, the first parameter should
be of type int and the second of type char. The match between arguments and parameters is important, for
parameters are simply variable that initialized to the values of the arguments when the function is invoked.
Lab Task 7(B): Programming Examples
Programming project lab7_01
Description: Write a C program that asks the user to enter two integers and find their sum
Source Code Output
#include<stdio.h> Enter two numbers: 56 98
int sum(int x, int y) Sum of 56 and 98 is 154
Prepared By: Dr. Tishna Sabrina, Asst. Professor EEE, UAP
Farhana Akter Mou, Lecturer
{
int s;
s =x+y;
return s;
}
int main()
{
int a,b,s;
printf ("Enter two numbers: ") ;
scanf("%d %d",&a,&b);
s=sum (a,b);/*Function call */
printf("Sum of %d and %d is %d\n",a,b,s);
return 0;
}
Programming project lab7_02
Description: Write a C program that asks the user to enter two integers and find the
maximum of them.
Source Code Output
#include<stdio.h> Enter two numbers:23 56
max(int x,int y); Maximum of 23 and 56 is 56
int main()
{
int a, b;
printf ("Enter two numbers:");
scanf("%d%d",&a,&b);
printf("Maximum of %d and %d is
%d\n",a,b,max(a,b));
return 0;
}
max(int x,int y)
{
if (x>y)
return x;
else
return y;
}
Programming project lab7_03
Description: Write a C program that returns the sum of squares of all odd numbers from 1 to 25.
Source Code Output
#include <stdio.h> The sum is: 2925
int func (void);
main( )
{
printf ("The sum is: %d\n", func( ) );
return 0;
}
Prepared By: Dr. Tishna Sabrina, Asst. Professor EEE, UAP
Farhana Akter Mou, Lecturer
int func()
{
int num, s=0;
for(num=1;num<=25;num++)
{
if(num%2!=0)
s+=num*num;
}
return s;
}
Programming project lab7_04
Description: Write a C program to find sum of digits of an integer.
Source Code Output
#include <stdio.h> Enter the number: 2437
int sum (int n); Sum of digits of 2437 is 16
main()
{
int num;
printf ("Enter the number: ") ;
scanf("%d",&num) ;
printf ("Sum of digits of %d is %d\n", num,
sum(num) );
return 0;
}
int sum (int n)
{
int i, sum=0, rem;
while (n>0)
{
rem=n%10;
sum+=rem;
n/=10;
}
return sum;
}
Lab TASK 7(C): Code Analyzer
Students will type the following codes in individual file and analyze the output.
Ca701.c #include <stdio.h>
void func(int a,int b);
main( )
{
func(2,3) ;
return;
}
Prepared By: Dr. Tishna Sabrina, Asst. Professor EEE, UAP
Farhana Akter Mou, Lecturer
void func(int a,int b)
{
int s;
s=a+b;
printf("Sum=%d",s);
}
Ca702.c #include<stdio.h>
main()
{
int x=5,y;
y=func (x) ;
printf("%d\n",y);
}
int func (int a)
{a=a*2;
return a;
}
Ca703.c #include<stdio.h>
void func (int a, int b);
main ( )
{
int i=5,j=10;
func(i/2,j%3) ;
}
void func(int a,int b)
{a=a/2;
b--;
printf("%d\t",a+b) ;
}
Lab Task 7(D): Home Work
(Submit at the next lab session as lab report)
HW01. Write a program using user defined function to print all the Armstrong numbers between 1
and 500. [An Armstrong Number is a number which is equal the sum of cubes of its digits.
For example, 153 is an Armstrong number, because 153 = 13+53+33 ]
HW02. Write a program using two separate functions to find the GCD (Greatest Common Divisor)
and LCM (Lowest Common Multiple) respectively of two given numbers. The LCM
function may call the GCD function and vice versa.
Prepared By: Dr. Tishna Sabrina, Asst. Professor EEE, UAP
Farhana Akter Mou, Lecturer