Chapter 3
Functions
FE – C Programming
Prof. Namrata Jiten Patel
Assistant Professor
Dept. of Computer Engineering,
SIES Graduate School of Technology
Objectives :To provide exposure to problem-solving by developing an
algorithm, flowchart and implement the logic using C programming
language
Outcomes: Learner will be able to…
1. Decompose a problem into functions and synthesize a complete
program.
Namrata Jiten Patel 2
Learning Outcomes
• Students will be able
• Discuss a function and how to use it benefits in a program
• Explain function declaration, function call and function
definition are constructed
• Discuss how variables are passed to functions
• Explain the scope rules mean in function and blocks.
• Learn about global and local variable
• Discuss about storage class specifier
• Highlight the basic concept of recursion and discuss the
technique of constructing recursive functions.
Namrata Jiten Patel 3
Concept of Function
• Function is a self contained block of program statements that
performs a particular task.
• It is often defined as a section of a program performing specific job .
• Originally function were subset of concept called as Subroutine .
Namrata Jiten Patel 4
Why are functions needed?
• It makes programs significantly easier to understand and maintain by
breaking up a program into easily manageable chunks .
• The main program can consist of a series of a function calls rather
than countless lines of code which can execute as many times as
necessary from different points in main program.
• The well-known functions may be re-used in multiple programs .
(example C standard library)
• Functions can also used to protect the data .This is related to local
data which are available only within their scope.
• By using functions different programmers working of one large
project can divided the workload by writing different functions.
Namrata Jiten Patel 5
Points to be noted
• A function can return only one value.
• A function type void does not return any value.
• There may be more than one return statement in a function ,but only one return
statement will be executed per call to the functions .
• If there are no parameters to a function, you can specify the parameter list as
void, as you have been doing in the case of the main() function
• Function to check whether a given year is a leap year or not.
• void leap_yr(int yr)
• {
• if((yr%4==0)&&(yr%100!=0)||yr%400==0)
• return 1;
• else
• return 0;
Namrata Jiten Patel 6
Function proto-type declaration
• The general form of function
Namrata Jiten Patel 7
Namrata Jiten Patel 8
Some of the examples of function
declaration
Namrata Jiten Patel 9
• There are two ways for prototyping functions.
• The most common method is simply to write the function declaration
with the arguments typed, with or without identifiers for each, such
as given example can
• be written as either of the following:
Namrata Jiten Patel 10
Function Definition
• The collection of program statements in C that describes the specifi c
task done by the function is called a function defi nition.
• It consists of the function header and a function body, which is a
block of code enclosed in parentheses.
• The definition creates the actual function in memory.
• Example:
Namrata Jiten Patel 11
Points to note
• There is no standard guideline about the number of parameters that
a function can have.
• C compliant compiler is required to support at least 31 parameters in
a function
• The number of parameters a function has also directly affects the
speed at which it is called—the more parameters, the slower the
function call.
Namrata Jiten Patel 12
1. Write a function that computes
x^n , where x is any valid number and
n an integer value
• void power(double x, int n) {
• double result = 1.0; Function
• for(int i = 1; i<=n; i++) Header
• {
• result *= x;
• }
• Print(“result%lf”,result); Return
Header
• return;
•}
Namrata Jiten Patel 13
return Statement
• The general form of the return statement is as follows:
• return expression;
• Or
• return(expression);
Namrata Jiten Patel 14
The expression can also include
function calls,
• if those functions return a numeric value!
• The following is a valid calling statement:
• x = power(power(2, 5), 2);
Namrata Jiten Patel 15
Function calling
• Function will carry out its expected action whenever it is invoked
(i.e. whenever the function is called) from some portion of a
program which means the program control passes to that of the
called function.
• . Once the function completes its task, the program control is
returned back to the calling function.
Namrata Jiten Patel 16
example
Namrata Jiten Patel 17
Function program example
• Sample program
Namrata Jiten Patel 18
Parameters:
Actual Parameter
Formal Parameter
• Actual Parameters :
The arguments that are passed in a function call are
called actual arguments. These arguments are defined
in the calling function. These are the variables or
expressions referenced in the parameter list of a
subprogram call. There is no need to specify datatype
in actual parameter.
• Formal Parameters :
These are the variables or expressions referenced in
the parameter list of a subprogram specification. The
datatype of the receiving value must be defined. The
scope of formal arguments is local to the function
definition in which they are used.
Namrata Jiten Patel 19
Actual Parameters Formal Parameters
When a function is called, the values (expressions) that The parameter used in function definition statement
are passed in the function call are called the arguments or which contain data type on its time of declaration is called
actual parameters. formal parameter.
These are the variables or expressions referenced in the These are the variables or expressions referenced in the
parameter list of a subprogram call. parameter list of a subprogram specification.
Actual Parameters are the parameters which are in calling Formal Parameters are the parameters which are in called
subprogram. subprogram.
There is no need to specify datatype in actual parameter. The datatype of the receiving value must be defined.
The parameters are written in function call are known as The parameters are written in function definition are
actual parameters. known as formal parameters.
Actual Parameters can be constant values or variable Formal Parameters can be treated as local variables of a
names. function in which they are used in the function header.
Namrata Jiten Patel 20
Crucial Points to be remembered
• The number and types of arguments must match the declared
types,otherwise the program causes an error.
• The arguments are converted as if by assignment ,to the declared
types of formal parameters.
• The arguments are converted to following default argument
promotions:
1. Type float is converted to double
2. Array and function names are converted to corresponding
pointers.
Namrata Jiten Patel 21
Call by Value mechanism
• The technique is to pass data to function is known as parameter
passing .
• Data is passed to a function using two techniques:
• Call by value
• Call by reference
Namrata Jiten Patel 22
Call by value
• A copy of data is made and the copy is sent to the function
• The copies of the value held by arguments are passed to function
call.
• Since only copies of value held in parameters are passed by the
function call to the formal parameters of the called function,the
value remains un-changed .
• Example:
Namrata Jiten Patel 23
Scope and Extent
• The region of the program over which the declaration of an identifier
is visible is called the scope of the identifier.
• The scope relates to the accessibility, the period of existence, and
the boundary of usage of variables declared in a statement block or
a function.
• These features in turn define whether a variable is local or global
in nature.
Namrata Jiten Patel 24
Concept of Global and Local Variables
•There are two common terms related to the
visibility or accessibility of a variable. They are
global and local variables.
•Actually global and local are the terms related
with lifetime.
•Lifetime is the period during execution of a
program in which a variable or function exists
Namrata Jiten Patel 25
Local Variable
• Variables declared within the function body are called local variables.
They have local scope.
• Local variables are automatically created at the point of their declaration
within the function body and are usable inside the function body.
• These variables only exist inside the specific function that creates them.
They are unknown to other functions and to the main program.
• The existence of the local variables ends when the function completes its
specific task and returns to the calling point.
• They are recreated each time a function is executed or called.
Namrata Jiten Patel 26
Global Variable
• Variables declared outside of all the functions of a program and accessible by
any of these functions are called global variables.
• The existence and region of usage of these variables are not confined to any
specific function body.
• They are implemented by associating memory locations with variable names.
• Global variables are created at the beginning of program execution and
remain in existence all through the period of the execution of the program.
• These variables are known to all functions in the program and can be used
by these functions as many times as may be required.
• They do not get recreated if the function is recalled.
Namrata Jiten Patel 27
Namrata Jiten Patel 28
Global Variable
• All global variables are declared outside of all the functions.
• There is no general rule for where outside the functions these should be
declared, but declaring them on top of the code is normally
recommended for reasons of scope
• If a variable of the same name is declared both within a function and
outside of it, the function will use the variable that is declared within it
and ignore the global one.
• If not initialized, a global variable is initialized to zero by default.
Namrata Jiten Patel 29
Example
1) Write a program that uses a function to swap values stored in
two integer variables to understand the concept of local and
global
variables.
#include <stdio.h>
void exchange(int, int);
int main()
{ /* main() program body starts here...*/
int a, b; /* local variables */
a = 5;
b = 7;
printf(“ In main: a = %d, b = %d\n”, a, b);
exchange(a, b);
printf(“\n Back in main:”);
printf(“a = %d, b = %d\n”, a, b);
return 0;
} /* main() program body ends here... */
Namrata Jiten Patel 30
void exchange(int a, int b)
{ /* function body starts here...*/
int temp; /* local variable */
printf(“\n In function exchange() before\
change: just received from main... a=%d\
and b=%d”,a,b);
temp = a;
a = b;
b = temp; /* interchange over */
printf(“\n In function exchange() after change:”);
printf(“a = %d, b = %d\n”, a, b);
} /* function body ends here...*/
Output:
In main: a = 5, b = 7
In function exchange() before change: just
received from main... a=5 and b=7
In function exchange() after change: a = 7, b = 5
Back in main: a = 5, b = 7
Namrata Jiten Patel 31
• The results depict that the program code above failed to exchange the
numbers between the variables in the function main().
• This happened because, firstly, the variables a and b in main() and that
within the function exchange() are not the same.
• The variables a and b within exchange() are local variables and are
created when the function is invoked, which means program control is
taken over by the function, and these are killed the moment program
control returns to the main() program.
• While calling the exchange() function from main(), copies of the values
held by a and b, which are local to main(), are handed over to separate
variables a and b that are local to the function exchange().
• Within this exchange() function, the task of exchanging the values
between its local variables a and b is carried out successfully, as is
evident from the messages displayed when the program is run.
• This in no way affects the values in variables a and b in the main().
Secondly, this exchanged copy of values in the variables is not passed
back from the function exchange() to the variables in main().
• Hence the values in the variables a and b within main() remained
untouched and unchanged
Namrata Jiten Patel 32
#include <stdio.h> temp = a;
void exchange(void);
int a, b; /* declaration of global variables
a = b;
*/ b = temp; /* interchange over
int main() */
{ /* main program starts here...*/ printf(“\n In function
a = 5; exchange() after change:”);
b = 7;
printf(“a = %d, b = %d\n”, a,
printf(“ In main: a = %d, b = %d\n”, a, b);
exchange(); /* function call, no parameters
b);
are passed */ } /* function body ends here*/
printf(“\n Back in main:”); Output
printf(“a = %d, b = %d\n”, a, b); In main: a = 5, b = 7
return 0;
In function exchange() before
} /* main program ends here */
void exchange(void)
change: just
{ /* function body starts here...*/ received from main... a=5 and
int temp; /* decl. of local variable in b=7
function*/ In function exchange() after
printf(“\n In function exchange() before\ change: a = 7, b = 5
change: just received from\
Back in main: a = 7, b = 5
main... a=%d and b=%d”,a,b);
Namrata Jiten Patel 33
Scope rules
• The region of the program over which the declaration of an identifier is
accessible is called the scope of the identifier.
• The scope relates to the accessibility, the period of existence, and the
boundary of usage of variables declared in a program.
• Scopes can be of four types.
block
file
function
function prototype
Namrata Jiten Patel 34
Block scope
• The identifier can only be used in the block in which it is declared.
• These variables are created at the point of their declaration inside
the block and cease to exist outside it.
• Outside the block, these variables are unknown and non-existent. For
blocks within blocks, termed as nested blocks, variables declared
outside the inner blocks are accessible to the nested blocks,
provided these variables are not redeclared within the inner block.
• The redeclaration of variables within the blocks bearing the same
names as those in the outer block, masks the outer block variables
while executing the inner blocks.
• In general, it is always better to use different names for variables not
common to outer and inner blocks to avoid unforced errors.
Namrata Jiten Patel 35
Write a program that illustrates the scope rules in blocks.
#include <stdio.h> Output
int main() in outer block x = 3 before
{ executing inner block
int x= 3; /* variable declaration in outer in inner block x = 45
block */ in outer block x = 3 after
printf(“\n in outer block x = %d before\ executing inner
executing inner block”, x); Block
{
int x= 45; /* variable declaration in • This program shows that because
inner the variable x has been redeclared
as 45 in the inner block, a local
block */ variable gets created in the inner
printf(“\n in inner block x = %d”, x); block. This variable is only
accessible and known to the inner
} block.
printf(“\n in outer block x = %d after
executing\
inner block”, x);
return 0;
} Namrata Jiten Patel 36
• Functions are considered as named block. Variables declared within a function
block can be used anywhere within the function in which they are defined. The
variable x declared in outer block has the block scope.
• Like blocks, functions can either be defined in parallel, where the functions are
placed one after the other and a function can be called from any other function.
But C does not allow functions to be nested, i.e. a function cannot be defined
within another function definition.
Namrata Jiten Patel 37
Function scope
• This applies only to labels. Normally labels are used with goto statement.
It simply means that labels can be used anywhere within the function in
which they are defined.
• This includes use before definition
Namrata Jiten Patel 38
File scope
• This means that the identifier can be used anywhere in the current fi le
after the declaration of the identifier.
• This applies to functions and all variables declared outside functions. File
scope variable is also known as global variable.
• File scope identifiers may be hidden by the block scope declarations
having same name.
Namrata Jiten Patel 39
Function prototype scope
• In order to improve readability and understandabilty, function
prototypes are usually written with ‘dummy’ variable names.
• For example
double max(double x, double y);
• The identifiers ‘x’ and ‘y’ have function prototype scope, which
terminates at the end of the prototype.
• This allows any dummy parameter names appearing in a function
prototype to disappear at the end of the prototype.
Namrata Jiten Patel 40
• Consider the following program:
#include <stdio.h>
int main(void)
{
void show(int x);
int x=10;
show(x);
return 0;
}
void show(int x)
{
printf(“\n %d”,x);
}
• The int variable name does not conflict with the parameter
name because the parameter went out of scope at the end of the
prototype. However, the prototype is still in scope.
Namrata Jiten Patel 41
Points to note
• In standard C, formal parameters in the function definition have the same
scope as variables declared at the beginning of the block that forms the
function body and therefore they cannot be hidden or redeclared by
declarations in the body.
• The following function definition, if used, will give error message at
compile time.
int sum(int x, int y)
{
int x=5;
return x+y;
}
• Compilation error message displayed
• In function ‘sum’:
• error: ‘x’ redeclared as different kind of symbol
• note: previous defi nition of ‘x’ was here
Namrata Jiten Patel 42
• How long memory will be associated with them is known as extent or
lifetime of a data object.
• The storage duration of the identifier determines its lifetime, either static
duration
(global lifetime) or automatic duration (local lifetime).
• The duration of an object describes whether its storage is allocated once
only, at program start-up, or is more transient in its nature, being
allocated and freed as necessary.
• Static duration means that the object has its storage allocated
permanently i.e. storage is allocated at or before the beginning of
program execution and the storage remain allocated until program
termination.
• Automatic duration means that the storage is allocated and freed as
necessary.
• The following rules specify whether an identifier has global (static) or
local (automatic) lifetime:
1. Global lifetime All functions have global lifetime.
• As do the identifiers declared at the top level (that is, outside all blocks in
the program at the same level of function defi nitions).
Namrata Jiten Patel 43
2. Local lifetime
An object (unless it is declared as static) is said to have local lifetime when it is
created on entry to a block or function and destroyed on exit from block or
function.
• Formal parameters and variables declared at the beginning of the block may
have local lifetime depending on the place of declaration.
• The data object created with the use of special library functions such as malloc()
or calloc() etc have dynamic duration and the storage remain allocated from the
time of creation at run time until program termination or until a call to special
library function free().
Namrata Jiten Patel 44
Storage Classes
Storage class specifiers for variables
• In C, the variables are declared by the type of data they can hold.
• The name of a variable is associated with a memory location within the
computer where the value assigned to the variable is stored in the form of
bits.
• During the execution of the program, these variables may be stored in the
registers of the CPU or the primary memory of the computer.
• To indicate where the variables would be stored, how long they would
exist, what would be their region of existence, and what would be the
default values, C provides four storage class specifiers that can be used
along with the data type specifiers in the declaration statement of a
variable.
• These four storage class specifiers are :
Automatic
External
Register
Static
Namrata Jiten Patel 45
• The general form of the variable declaration statement that includes the
storage class specifier is given as follows:
storage_class_specifi er data_type variable_name;
1. The storage class – auto
• By default, all variables declared within the body of any function are
automatic.
• The keyword auto is used in the declaration of a variable to explicitly
specify its storage class.
auto char any_alpha;
• all local variables in a function, by default, belong to automatic storage
class
• These variables are stored in the primary memory of the computer.
• Local variables declared within nested blocks in a function belong by
default to the automatic storage class
Namrata Jiten Patel 46
Example Auto storage class
#include <stdio.h>
int main(void)
{
auto int a =5;
int i;
printf(“\n a = %d”,a);
{
int a = 10;
printf(“\n a = %d”,a);
printf(“\n i = %d”,i);
}
printf(“\n a = %d”,a);
return 0;
}
Output
a=5
a = 10
i = 4199232
a=5 Namrata Jiten Patel 47
The storage class – register
• Values stored in registers of the CPU are accessed in much lesser time
than those stored in the primary memory.
• To allow the fastest access time for variables, the register storage class
specifier is used.
• The keyword for this storage class is register.
• The variables thus specified are stored in some register of the CPU.
• In most C compilers, the register specifier can only be applied to int and
char
type variables
• Arrays cannot be stored in a registers (but still depend on compilers and
OS)
• The existence of the variables with the storage class specifier register is
restricted within the region of a function or a block where it has been
declared and exists as long as the function or block remains active.
• The default value within this variable is unknown, which is interpreted as
garbage.
• Storage class of a global variable cannot be specified as register.
• Points to
Namrata Jiten Patel 48
Points to note
• Global variables with register storage class are not allowed.
• In C, it is not possible to obtain the address of a register variable by using
‘&’ operator.
• In addition, the only storage class specifier that can be used in a
parameter declaration is register.
Namrata Jiten Patel 49
• A static local variable is allotted a permanent storage location in the
primary memory.
• This variable is usable within functions or blocks where it is declared and
preserves its previous value held by it between function calls or between
block re-entries.
• However, once a function is invoked, the static local variable retains the
value in it and exists as long as the main program is in execution.
• The external static variables in a program file are declared like global
variables with the keyword static preceding its declaration statement.
• These static variables are accessible by all functions in the program file
where these variables exist and are declared.
• The external static variables are not available to functions defined earlier
in the same file or not accessible to functions defined in other files
although these may use the extern keyword.
• These variables exist throughout the period of the main program
execution.
• Such variables get stored in the primary memory
Namrata Jiten Patel 50
The storage class – static
• Two kinds of variables are allowed to be specified as static variables:
local variables and global variables.
• The local variables are also referred to as internal static variables while
the global variables are also known as external static variables.
• The default value of a static variable is zero.
• To specify a local variable as static, the keyword static precedes its
declaration statement.
Namrata Jiten Patel 51
• Write a C program that void show(void)
illustrates the use local static {
variables and functions.
static int i;
#include <stdio.h>
printf(“\n i=%d”,i);
int main()
i++;
{
}
void show(void);
Output
printf(“\n First Call of show()”);
First Call of show()
show();
i=0
printf(“\n Second Call of show()”);
Second Call of show()
show();
i=1
printf(“\n Third Call of show()”);
Third Call of show()
show();
i=2
return 0;
}
Namrata Jiten Patel 52
The storage class – extern
• A program in C, particularly when it is large, can be broken up into
smaller programs.
• After compiling, each program file can be joined together to form the
large program.
• These small program modules that combine together may need some
variables that are used by all of them.
• In C, such a provision can be made by specifying these variables,
accessible to all the small program modules, as an external storage class
variable.
• These variables are global to all the small program modules that are
formed
• as separate files.
• The keyword for declaring such global variables is extern.
• Such global variables are declared like any other variable in one of the
program modules while the declaration of these variables is preceded
with the keyword extern in all other combining program modules.
Namrata Jiten Patel 53
• These variables remain in existence as long as the program is in
execution and their existence does not terminate upon the exit of a
function or a block or a program module from its state of execution.
• These variables are stored in the primary memory and their default value
is zero
Namrata Jiten Patel 54
/******************************/
/*******************************/
/* Program fi le: pgm1.c */
/* Program fi le: pgm2.c */
/*******************************/
/*******************************/
#include <stdio.h>
extern int i;
#include “pgm2.c” /*** link program
pgm2.c ***/ /***** function definition of show()*****/
int i; /*** external/global decl.**/ void show() /*** function header ***/
void show(void); /*** function { /*** fn. body starts..**/
prototype ***/ printf(“\n Value of i in pgm2.c=%d”,i);
int main() } /*** fn. body ends.. **/
{ Output
i=10; Value of i in pgm2.c=10
show(); /* call to function in program fi Value of i in pgm1.c=10
le pgm2.c */
printf(“\n Value of i in pgm1.c=%d ”,i);
return 0;
} /****** pgm1.c fi le ends
***********/
Namrata Jiten Patel 55
Namrata Jiten Patel 56
Storage Class Specifiers for Functions
• The only storage class specifiers that may be assigned with functions are
extern and static.
• The extern signifies that the function can be referenced from other files-
that is, the function name is exported to the linker.
• The static signifies that the function cannot be referenced from other
files- that is the function name is not exported to the linker.
• If no storage class appears in a function definition, extern is presumed.
Namrata Jiten Patel 57
Recursion
A recursive function is one that calls itself directly or indirectly to
solve a smaller version of its task until a final call which does not
require a self-call.
Recursion is like a top–down approach to problem solving; it divides
the problem into pieces or selects one key step, postponing the rest.
How iteration is different from Recursion
Iteration is more of a bottom–up approach; it begins with what is
known and from this constructs the solution step by step
Namrata Jiten Patel 58
Why Recursion is needed
Decomposition into smaller problems of same type
Recursive calls must diminish problem size
Necessity of base case
Base case must be reached
It acts as a terminating condition. Without an explicitly defi ned base
case, a recursive function would call itself indefinitely.
It is the building block to the complete solution. In a sense, a
recursive function determines its solution from the base case(s) it
reaches
Namrata Jiten Patel 59
What is Base Case
• An instance of a problem the solution of which requires no further
recursive calls is known as a base case.
Namrata Jiten Patel 60
Sample of Recursion
Namrata Jiten Patel 61
Example of Recursion
#include <stdio.h>
//function for factorial
long int factorial(int n)
{
if(n==1) { return 1;}
return n*factorial(n-1);
}
int main()
{
int num;
long int fact=0;
printf("Enter an integer number: ");
scanf("%d",&num);
fact=factorial(num);
printf("Factorial of %d is = %ld",num,fact);
printf("\n");
return 0;
}
Namrata Jiten Patel 62
Example of Recursion
#include <stdio.h>
int fibonacci(int i) {
if(i == 0) {
return 0;
}
if(i == 1) {
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}
int main() {
int i;
for (i = 0; i < 10; i++) {
printf("%d\t\n", fibonacci(i));
}
return 0;
}
Namrata Jiten Patel 63
#include <stdio.h>
//function for calculating power
long int getPower(int b, int p)
{
long int result = 1;
if (p == 0)
return result;
Calculate power of a
result = b * (getPower(b, p - 1)); //call function again number program using
} recursion
int main()
{
int base, power;
long int result;
printf("Enter value of base: ");
scanf("%d", &base);
printf("Enter value of power: ");
scanf("%d", &power);
result = getPower(base, power);
printf("%d to the power of %d is: %ld\n", base, power, result);
return 0;
}
Namrata Jiten Patel 64
Predefined functions
Function name Math name Value
Abs(x) Absolute value abs(-12)=12
Fabs(x) Absolute value The absolute value of -
344 is 344.000000
Pow(x,y) Raise to power Value 8.0 ^ 3 =
512.000000
Exp(x) exponential The exponential value of
1.000000 is 2.718282
Log(x) Natural logarithm log(2.700000) = 0.993252
Sin(x) sine
Log10(x) Common logarithm
Cos(x) cosine The cosine of 60.000000
is 0.500000 degrees
Tan(x) tangent
Ceil(x) Higher value ceil(3.3)=4.000000
Floor(x) Lower value val3 = -2.8; returns
value3 = -2.0
Sqrt(x) Square root Square root of
225.000000 is 15.000000
Namrata Jiten Patel 65
Passing Arrays to function
• Arrays can also be arguments of functions. When an array is passed
to a function, the address of the array is passed and not the copy of
the complete array
• Therefore, when a function is called with the name of the array as
the argument, address to the first element in the array is handed
over to the function.
• They are never called by value because of content getting
manipulated .
Namrata Jiten Patel 66
Example
#include <stdio.h>
void doubleThem(int [], int);
/* declaration of function */
int main(void)
{
int myInts[10] = {1,2,3,4,5,6,7,8,9,10};
int size=10;
printf(“\n\n The given numbers are :”);
for (i = 0; i < size; i++)
printf(“%d,”,myInts[i]);
doubleThem(myInts,size); /* function call */
printf(“\n\n The double numbers are : ”);
for (i = 0; i < size; i++)
printf(“%d,”,myInts [i]);
return 0;
}
/******* function defi nition *******/
void doubleThem(int a[], int size)
{
int i;
for(i = 0; i < size; i++)
{
a[i] = 2 * a[i];
}
}
Namrata Jiten Patel 67
Write a program that uses a function to find the average age of students of
a class chosen for a junior quiz competition.
#include <stdio.h>
#defi ne SIZE 50
fl oat avg_age(int [],int);
int main(void)
{
int i,b[SIZE],n;
fl oat average;
printf(“\n How many students? \n%”);
scanf(“%d”,&n);
printf(“\n Enter the age of students \n”);
for(i=0;i<n;i++)
scanf(“%d”,&b[i]);
average=avg_age(b,n);
printf(“\n the average age of students =%f”,
average);
return 0;
} float avg_age(int a[], int n){
int j;
float sum=0.0;
for(j=0;j<n;j++)
sum=sum+a[j];
return sum/n;
}
68
Thank You!!
[email protected]
Namrata Jiten Patel 69