Functions
e Using functions
e Function declaration
e Function definition
¢ Function call
© Scope of variables
® Call-by-value and call-by-reference
© Storage classes
© Recursive functions
© Tower of Hanoi
4.1 INTRODUCTION
C enables programmers to break up a program into
segments commonly known as functions, each of which
can be written more or less independently of the others.
Every function in the program is supposed to perform a
well-defined task. Therefore, the code of one function is
completely insulated from the other functions.
Every function interfaces to the outside world in terms
of how information is transferred to it and how results
generated by it are transmitted back. This interface is
specified by the function name. For example, look at Figure
4.1 which explains how the main() function calls another
function to perform a well-defined task.
funcl1()
{
Statement Block;
Otte
- acanekd
Figure 4.1 The main() function calls func1 ()
From the figure we can see that main () calls a function
named funci (). Therefore, main () is knownas the calling
function and funci() is known as the called function. The
moment the compiler encounters a function call, instead of
executing the next statement in the calling function, the
control jumps to the statements that are part of the called
function. After the called function is executed, the control
is returned back to the calling function.
It is not necessary that the main() function can call
only one function, it can call as many functions as it wants
and as many times as it wants. For example, a function
call placed within a for loop, while loop, or do-while
loop can call the same function multiple times until the
condition holds true.
Another point is that it is not only the main() function
that can call other functions. A function can call any other
function. For example, look at Figure 4.2 which shows one
function calling another, and this function in tum calling
some other function. From this we see that every function
encapsulates a set of operations and when called it retumms
information to the calling function.
4.1.1 Why are Functions Needed?
Let us analyse the reasons for segmenting a program
into manageable chunks as it is an important aspect of
programming,
| 106 | Programming in C
main() funel()
{ {
funel () ; fune2();
return 0; return:
Figure 4.2 Functions calling another functions
* Dividing a program into separate well-defined
functions facilitates each function to be written and
tested separately. This simplifies the process of getting
the total program to work. Figure 4.3 shows that the
main() function calls other functions for dividing the
entire code into smaller sections (or functions). This
approach is referred to as the top-down approach.
Main function
Function A | Function C |
|
Function B1 | iaien B2
Figure 4.3. Top-down approach of solving a problem
Function B |
ae
e Understanding. coding, and testing multiple separate
functions are far easier than doing it for one big function.
e If a big program has to be developed without the use
of any function other than main() function, then there
will be countless lines in the main() function and
maintaining this program will be very difficult. A large
program size is a serious issue in micro-computers
where memory space is limited.
© All the libraries in C contain a set of functions that the
programmers are free to use in their programs. These
functions have been pre-written and pre-tested, so the
programmers can use them without worrying about their
code details. This speeds up program development, by
allowing the programmer to concentrate only on the
code that he has to write.
« When a big program is broken into comparatively
smaller functions, then different programmers working
on that project can divide the workload by writing
different functions.
func2() func3()
( {
” Bae
opt return;
return; )
e Like C libraries, programmers can also write their
functions and use them at different points jn the
main program or in any other program that needs jp,
functionalities.
Consider a program that executes a set of instructions
repeatedly n times, though not continuously. In case the
instructions had to be repeated continuously for n times,
they can be placed within a loop. But if these instructions
have to be executed abruptly from anywhere within the
program code, then instead of writing these instructions
wherever they are required, a better idea is to place these
instructions in a function and call that function wherever
required. Figure 4.4 explains this concept.
Figure 4.4 Function funci() called twice from main ()
4.2 USING FUNCTIONS
In the second chapter we have discussed that when we
execute a C program, the operating system calls the
main() function of the program which marks the entry
point for the execution. When the program is executed, the
main() returns some value to the operating system.
Any function (including main()) can be compared
to a black box that takes in input, processes it, and then
produces the result. However, we may also have a function
that does not take any inputs at all, or the one that does not
return anything at all.
While using functions we will be using the followin
ul
terminologies: ;
e Afunction f that uses another function 8 is known as th
Re . 8 the
calling function and gq is known as the
The inputs thata function t
parameters
called function,
akes are known as arguments/
When a called function returns some result back to the
calling function, it is said to return that result
The calling function may or may not pass parameters
to the called function. If the called function accepts
arguments, the calling function will Pass parameters
else it will not do so. ;
Function declaration is a declaration statement that
identifies a function with its name, a list of arguments
that it accepts, and the type of data it returns,
Function definition consists of a function header
that identifies the function, followed by the body of
the function containing the executable code for that
function.
4.3 FUNCTION DECLARATION/
FUNCTION PROTOTYPE
Before using a function, the compiler must know about
the number of parameters and the type of parameters that
the function expects to receive and the data type of the
value that it will return to the calling function. Placing
the function declaration statement prior to its use enables
the compiler to make a check on the arguments used while
calling that function.
The general format for declaring a function that accepts
some arguments and returns some value as a result can be
given as:
return_data_type function_name(data_type
variablel, data_type variable2,...);
Here, function_name is a valid name for the function.
Naming a function follows the same rules as naming
variables. A function should have a meaningful name that
must specify the task that the function will perform. The
function name is used to call it for execution in a program.
Every function must have a different name that indicates
the particular job that the function does.
return data_type specifies the data type of the value
that will be returned to the calling function as a result of
the processing performed by the called function.
Functions | 107 |
data _ type variablel, data_type variable2,
is a list of variables of specified data types. These variables
are passed from the calling function to the called function.
They are also known as arguments or parameters that the
called function accepts to perform its task. Table 4.1 shows
examples of valid function declarations in C.
Table 4.1 Valid function declarations
Function declaration
Use of the function
Return data type
char convert_to_
uppercase (char ch);
Converts a character to upper case.
The function receives a character as
an argument, converts it into upper
case and returns the converted
character back to the calling |
function.
Function name
float avg (int a, int b);
Calculates average of two integer
numbers a and b received as
arguments. The function returns a
floating point value. |
int find_largest (int
Finds the largest of three |
numbers— a, b, and c received as
(float a, float b);
— Variable 1
a, int b, int c);
arguments. An integer value which
Data type of is the largest of the three numbers
variable is returned to the calling function.
double multiply Multiplies two floating point
numbers a and b that are received
as arguments and returns a
double value.
void swap
(int a, int b);
Swaps or interchanges the value of
integer variables a and b received
as arguments. The function returns
no value, therefore the return type
is void.
void print(void);
The function is used to print
information on screen. The
function neither accepts any
value as argument nor returns
any value. Therefore, the return
type is void and the argument list
contains void data type.
Things to remember about function declaration:
Programming Tip:
Though optional,
use argument names
in the function
declaration.
e After the declaration of every
function, there should be a
semicolon. If the semicolon
is missing, the compiler will
generate an error message.
¢ The function declaration is global.
Therefore, the declared function
can be called from any point in the
program.
| 108 | Programming in C
e Use of argument names in the function declaration
statement is optional. So both declaration statements
are valid in C.
int func(int, char, float);
or
int func(int num, char ch, float frum) ;
eA function cannot be declared within the body of
another function.
e A function having void as its retum type cannot retum
any value
e A function having void as its parameter list cannot
accept any value. So the function declared as
void print (void) ;
or
void print ()
does pot accept any input/arguments from the calling
functon
e if the function declaration does not specify any return
type, then by default, the function returms an integer
value. Therefore when a function is declared as
sum{int a, int b);
Then the function sum accepts two integer values from
the calling function and in tum retums an integer value
to the caller.
e Some compilers make it compulsory to declare the
function before its usage while other compilers make
i optional. However, it is a good practice to always
declare the function before its usage as it allows error
checking on the arguments in the function call.
4.4 FUNCTION DEFINITION
When 2 function is defined, space is allocated for that
function in the memory. A function
Programming Tip: § definition comprises two parts:
it is an error to
© Function header
place 2 semicolon i
after the function ¢ Function body
header in the The syntax of a _ function
function definition. definition can be given as:
return data type function name (data type
variablel, data type variable2,...)
statements
return (variable) ;
The number of arguments and the order of argume, ;
the function header must be same as that given sin
function declaration statement. Y the
While return aii
type function _ name (dat,
type variablel, data
variable2,..) is known ve pe
function header, the rest of .
portion comprising of Progra ¢
statements within { } is the ty
tion body which contains the a vs
to perform the specific task. .
The function header is same as function declaration
The only difference between the two is that a function
header is not followed by a semicolon. The list of variables
in the function header is known as the formal Parameter
list, The parameter list may have zero or more Parameters
of any data type. The function body contains instructions
to perform the desired computation in a function,
The function definition itself
Programming Tip:
The parameter
list in the function
definition as well as
function declaration
must match,
Programming Tip: = can act as an implicit function
Afunction can declaration. So the programmer
be defined either may skip the function declaration
before or after statement in case the function is
main().
defined before being used.
The argument names in the function declaration and
function definition need not be the same. However,
the data types of the arguments specified in function
declaration must match with that given in function
definition.
4.5 FUNCTION CALL
The function call statement invokes the function. When
a function is invoked the compiler jumps to the called
function to execute the statements that are part of that
function. Once the called function is executed, the program
control passes back to the calling function.
Function call statement has the following syntax:
function_name(variablel, variable2, ...);
When the function declaration is present before the
function call, the compiler can check if the correct number
and type of arguments are used in the function call and the
returned value, if any, is being used reasonably.
Function definitions are often placed in separate header
files which can be included in other C source files that
wish to use these functions. For example, the header file
stdio.h contains the definition of scanf and printf
functions, We simply include this header file and call these
functions without worrying about the code
functionality ‘0 implement
their Tul =
ust of variables used in function call is known as actual
parameter list. The actual parameter list may contain
variable names, expressions, or constants,
4.5.1 Points to Remember While Calling
Functions
The following points are to be kept in mind while calling
funchons:
e Function name and the number and type of arguments
in the function call must be same
Programming Tip: as that given in the function
A logical error will declaration and function header of
degenerated ifthe the function definition.
arguments in the
aes
athe fun ore than what
pa It is specified to accept then
the extra arguments will be
discarded.
e Ifthe parameters passed to a function are less than what
it is specified to accept then the unmatched arguments
will be initialized to some garbage value.
« Names (and not the types) of variables in function
declaration, function call, and header of function
definition may vary.
¢ If the data type of the argument passed does not match
with that specified in the function declaration then either
the unmatched argument will be initialized to some
garbage value or a compile time error will be generated.
* Arguments may be passed in the form of expressions
to the called function. In such cases, arguments are first
evaluated and converted to the type of formal parameter
and then the body of the function gets executed.
* The parameter list must be separated with commas.
* Ifthe return type of the function is not void, then the value
returned by the called function may be assigned to some
variable as shown in the following statement.
variable name = function_name(variablel,
variable2, ...);
Let us now try writing a program using function.
1. Write a program to add two integers using functions.
#include <stdio.h>
// FUNCTION DECLARATION
Functions | 109 |
int sum(int a, int b);
int main()
{
int numl, num2, total = 0;
printf ("\n Enter the first number: ");
scanf ("%d", &numl) ;
printf ("\n Enter the second number:
scanf ("%d", &num2) ;
total = sum(numl1, num2) ;
// FUNCTION CALL
printf("\n Total = %d", total);
return 0;
// FUNCTION DEFINITION
int sum (int a, int b) // FONCTION HEADER
{ // FUNCTION BODY
int result;
result = a + b;
return result;
Output
Enter the first number: 20
Enter the second number: 30
Total = 50
The variables declared within the function and its
parameters are local to that
function. The programmer may
‘ use same names for variables in
void as the return : é : s
other functions. This eliminates
type when the " Oe. ;
function is expected € need for thinking and keeping
toreturnavalueto Mique names for variables
the calling function. declared in ail the functions in the
program.
In the sum() function, we have declared a variable
result just like any other variable. Variables declared
within a function are called automatic local variables
because of two reasons.
First, they are local to the function. So, their effect (in
terms of scope, lifetime, or accessibility) is limited to
the function. Any change made to these variables is
visible only in that function.
¢ Second, they are automatically created whenever the
function is called and cease to exist after control exits
the function,
A function cannot be used on the left side of an
assignment statement, Therefore writing, func (10) =—
100; is invalid in C, where func is a function that accepts
an integer value, :
Programming Tip:
It is an error to use
the execution
calling function.
the program
on at the point
on call. Refer Figure
rom the called function
ng function when the
nent is encountered.
return statement may or may
retum a value to the calling
function. The syntax of return
‘statement can be given as
return <expression>;
on is placed in between angular
specifying an expression is optional.
return value of the function is undefined.
The expression, if present, is converted to the type
returned by the function. A function that has void as
its return type cannot return any value to the calling
function. So in a function that has been declared with
retum type void a return statement containing an
expression generates a warning and the expression is not
evaluated.
For functions that have no return statement, the
contro! automatically returns to the calling function after
the last statement of the called function is executed. In
other words an implicit return takes place upon execution
of the last statement of the called function, and control
automatically returns to the calling function.
Note
The programmer may or may not place the expression in
@ return statement within parentheses.
By default, the return type of a function is int.
A function may have more than one return statement. For
example, consider the program
Programming Tip: .
en below.
When the value said ai
returned by a #include <stdio.h>
functi ‘ j #include <conio.h>
» int check_relation(int a,
to a variable, then ae
the returned value int main()
isconvertedtothe {
type of the variable int a=3, b=5, tes;
receiving it. elrser();
res = check relation(a, b);
if(res==0) // Test the returned va),,,
printf ("\n EQUAL") ; 2
if (res==1)
printf("\n a is greater than b"),
if (res==-1)
printf("\n a is less than b"),
getch () ;
return 0;
}
int check_relation(int a, int b)
Programming Tip: if (a==b)
An error is return 0;
generated when else if (a>b)
the function does return 1;
not return data of ae
return -1;
Output
a is less than b
In the above program there are multiple return
statements, but only one of them will get executed
depending upon the condition. The return statement
like the break statement, is used
Programming Tip: to cause a premature termination
A function that of the function.
does not return An expression appearing in a
any value cannot return statement is converted to
be placed on the return type of the function in
the right side of which the statement appears. If no
the assignment implicit conversion is possible, the
operator. return Statement is invalid. Since
the return type of the function
check _relation() is int, so the result either 0, 1, or
-1 is evaluated as an integer.
We have mentioned earlier that the variables declared
inside the function cease to exist after the last statement
of the function is executed. So how can we return the
value of sum to the program that adds two integers using a
function? The answer to this question is that a copy of the
value being returned is made automatically and this copy
is available to the return point in the program.
4.6.1 Using Variable Number of Arguments
Some functions have a variable number of arguments
and data types that cannot be known at the compile time.
Typical examples of such functions include the printf ()
and scanf() functions. ANSI C offers a symbol called
ellipsis to handle such functions. The ellipsis consists of
three periods (...). It can be used as:
got func(char ch, << 3)'s
—_
The function declaration statement given above states
that func is a function that has an arbitrary number and
type of arguments. However, one must ensure that both the
function declaration and function definition should use the
ellipsis symbol.
‘e PASSING PARAMETERS To
When a function is called, the calling function may have
to pass some values to the called function. We have been
doing this in the Programming examples given so far,
We will now leam the technicalities involved in passing
arguments parameters to the called function.
There are (wo ways in which arguments or parameters
an be passed to the called function. They include:
. Call by value in which values of variables are passed by
the calling function to the called function. The programs
that we have written so far call functions using call-by-
value method of passing parameters.
® Call by reference in which address of variables are
passed by the calling function to the called function.
4.7.1 Call by Value
Tull now, we had been calling functions and passing
‘arguments to them using call-by-value method. In the call-
by-value method, the called function creates new variables
to store the value of the arguments passed to it. Therefore,
the called function uses a copy of the actual arguments to
perform its intended task.
If the called function is supposed to modify the value of
the parameters passed to it, then
Programming Tip: ‘he change will be reflected only
tt is legal to have in the called function. In the
mulnple return calling function no change will be
statements in C. made to the value of the variables.
This is because all the changes
were made to the copy of the variables and not to the
actual variables.
Te understand this concept, consider the code given
below. The add() function accepts an integer variable
mum and adds 10 to it. In the calling function, the value of
num = 2. In add(), the value of num is modified to 12 but
in the calling function the change is not reflected.
tinclude <stdio.h>
void edd(int n);
int main()
__Funetions_| 111 |
int num « 2;
printf ("\n The value of num before
calling the function » %d", num);
add (num) ;
printf ("\n The value of num after calling
the function = %d", num) ;
return 0;
void add(int n)
{
hen + 10;
printf ("\n The value of num in the called
function = %d", n);
)
Output
The value of num before calling the function = 2
The value of num in the called function = 12
The value of num after calling the function = Z
Since the called function uses a copy of num, the value
of num in the calling function remains untouched. This
concept can be more clearly understood from Figure 4.5.
al =
num in the calling function num in the calling function,
is known as n in the
ad
called function
num in the calling function
3
remains unchanged
n is modified in the
called function
Figure 4.5 Call-by-value method of argument passing
In the above program, the called function could not
directly modify the value of the argument that was
passed to it. In case the value has to be changed, then the
programmer may use the return statement. This is shown
in the following code.
#include <stdio.h>
int add (int n);
int main()
int num = 2;
printf("\n The value of num before
calling the function = td", num);
a oe... a
a. adalint n)
Rene 10;
printf (*\n The valve of num in the called
function = td*, a);
return a;
}
Ougrat
‘The value of mum before calling the function = 2
The value of mum in the called function = 12
The walue of mum after calling the function = 12
The following points are to be noted while passing
arguments to a function using the call-by-value method.
¢ When amguments are passed by value, the called
funchon creates new vanables of the same data type as
the arguments passed to it.
. The values of the arguments passed by the function are
copied mto the newly created variables.
* Amguments are called by value when the called function
does mot need to modify the values of the original
variables in the calling function.
* Walues of the variables in the calling function remain
unaffected when the arguments are passed using call by
value techmigue.
Therefore, call-by-walue method of passing arguments
to 2 function must be used only in two cases:
© When the called function does not need to modify the
value of the actual parameter. It simply uses the value of
the parameter to perform its task.
e When you want that the called function should only
temporarily modify the value of the variables and not
permanently. So although the called function may
modify the value of the variables,
Programming Tip: = these variables remain unchanged
‘Using call by in the calling function.
value method of
econ Pros and Cons
. The biggest advantage of using
ae call-by-value technique to
rere onelen pass arguments to the called
function is that arguments can be
variables (e.g., x), literals (e.g.,
6), or expressions (¢.g., x+1).
The disadvantage is that copying data consumes addition
storage space, In addition, it can take a lot of time to al
thereby resulting in performance penalty, especial ly itty
function is called many times.
4.7.2 Call by Reference
When the calling function passes arguments to the Called
function using call-by-value method, the only way to
return the modified value of the argument to the caller is
explicitly using the return statement. The better option
when a function wants to modify the value of the argumen,
is to pass arguments using call-by-reference technique,
In call by reference, we declare the function parameters
as references rather than normal variables. When this jg
done any changes made by the function to the arguments
it receives are visible in the calling function.
To indicate that an argument is passed using cal] by
reference, an asterisk (*) is placed after the type in the
parameter list. This way, changes made to the parameter
in the called function will then be reflected in the calling
function.
Hence, in call-by-reference method, a function receives
an implicit reference to the argument, rather than a copy of
its value. Therefore, the function can modify the value of
the variable and that change will be reflected in the calling
function as well. The following program uses this concept.
To understand this concept, consider the code given
below.
#include <stdio.h>
void add (int *n);
int main()
int num = 2;
printf ("\n The value of num before
calling the function = %d", num);
add (&num) ;
printf("\n The value of num after calling
the function = %d", num);
return 0;
void add(int *n)
{
*n = *n + 10;
printf("\n The value of num in the called
function = %d", *n);
Output
The value of num before calling the function = 2
The value of num in the called function = 12
The value of num after calling the function = 12
<3
——
Advantages
The advantages of using the call-by-reference technique
of passing arguments are as follows:
@ Since arguments are not copied into new variables, it
provides greater time and space efficiency
© The called fancthon can change the Value of the argument
‘and the change is reflected in the calling function.
® Areturn statement can retum only one value. In case
we need to retum multiple values, pass those arguments
dy reference.
Disadvantages
However, the side-effect of using this technique is that
‘when an argument is passed using call by address, it
Becomes difficult to tell whether that argument is meant
Br wput, output, or both.
Now let us write a few programs that use both the call-
—_—
‘2. Wiite a function to swap the value of two variables.
include «<stdio.h>
void swap_call_by val (int, int);
void swap_call by ref(int *, int *);
int maint!)
i
imt @=1, be2, c=3, dea;
printf ("\n In main(), a = %d and b = ta",
a,b);
Swap_call by vali(a, b);
Printf("\n In main(), a = td and b «= a",
a, bd);
printf (*\n\n In main(), c = td and d =
8d". c, d);
Swap_call by ref (&c, &d);
// @G@ress of the variables is passed
printfi*\n In main(), c = td andd =
td", c, d);
return 0;
}
void swap_call by val(int a, int b)
int temp;
temp = a;
i a=-b;
: q b = temp;
f printf(*\n In function (Call By Value
Method) a = $d and b « td", a, b);
bay )
~ void swap_call by ref(int *c, int *d)
{
iat temp;
temp = °c;
// *aperator used to refer to the value
Functions | 113 |
*e = *d;
*d «= temp;
printf ("\n In funetion (Call By Reference
Method) @ « td and d « 4d", *c, *d);
)
Output
In main(), a= 1 and b= 2
In function (Call By Value Method) a + 2 and
bel
In main(), a = 1 and b « 2
In main(), ¢ = 3} and d= 4
In function (Call By Reference Method) c = 4
and d-.3
In main(), ¢ = 4 andd« 3
3. Write a program to find biggest of three integers using
functions.
#include <stdio.h>»
int greater(int a, int b, int c);
int main()
int numl, num2, num3, large;
printf ("\n Enter the first number: ") ;
scanf ("%d", &num1) ;
printf ("\n Enter the second number: ") ;
scanf ("td", &num2) ;
printf ("\n Enter the third number: ");
scanf ("%d", &num3) ;
large = greater(num1, num2, num3) ;
printf("\n Largest number = %d", large);
return 0;
}
int greater(int a, int b, int c)
if(a>b && a>c)
return a;
if (b>a && b>c)
return b;
else
return c;
}
Output
Enter the first number : 45
Enter the second number: 23
Enter the third number : 34
Largest number = 45
4. Write a program to calculate area of a circle using
function.
#include <stdio.h>
float cal_area(float r);
| 114 |_ Programming inc
int main()
{
float area, radius;
printf("\n Enter the radius of the
circle: ");
scanf("%tf", &radius) ;
area = cal _area(radius) ;
printf("\n Area of the circle with radius
%f = %f", radius, area) ;
return 0;
}
float cal_area(float radius)
)
Output
Enter the radius of the circle: 7
Area of the circle with radius 7 = 153.83
return (3.14 * radius * radius) ;
5. Write a program to convert time to minutes.
#include <stdio.h>
#include <conio.h>
int convert_time_in_mins(int hrs, int
minutes) ;
int main()
{
int hrs, minutes, total _mins;
printf ("\n Enter hours and minutes: ");
scanf ("td %d", &hrs, &minutes) ;
total_mins = convert_time_in_mins(hrs,
minutes) ;
printf("\n Total minutes = %d", total_
mins) ;
getch();
return 0;
}
int convert_time_in mins(int hrs, int mins)
mins = hrs*60 + mins;
return mins;
)
Output
Enter hours and minutes: 4 30
Total minutes = 270
6. Write a program to calculate P(n/r).
#include <stdio.h>
#include <conio.h>
int Fact (int);
int main()
int n, r;
float result;
clrscr() ;
printf ("\n Enter the value of pn: »
scanf ("td", &n) ;
printf ("\n Enter the value of r: ),
scanf ("%td", &r);
result = (float) Fact (n)/Fact (r) ;
printf ("\n P(n/r): P(%d)/(%d) = S.2E0
r, result); tay
getch() ;
return 0;
);
int Fact (int num)
{
int fol, 17
for (i=num; i>=1;i--)
f= ©" 1;
return f;
)
Output
Enter the value of n: 4
Enter the value of r: 2
P(n/r): P(4)/(2) = 12.00
7. Write a program to calculate C(n/r).
#include <stdio.h>
#include <conio.h>
int Fact (int) ;
int main()
{
int n, 7;
float result;
clrscr() ;
printf ("\n Enter the value of n: ");
scanf ("%d", &n) ;
printf ("\n Enter the value of r: ");
scanf ("%d", &r) ;
result = (float) Fact (n) / (Fact (r)*Fact (n-r));
printf("\n C(n/r) : C(%d/%d) = %.2f", n,
r, result) ;
getch() ;
return 0;
int Fact (int num)
int ted, i;
for (i=num; i>=1;i--)
f = £*i;
return f;
}
Output
Enter the value of n: 4
Enter the value of r: 2
C(n/r): C(4)/(2) = 6.00
g, Write a program to sum the series
+ cw t Mint.
#include <stdio.h>
ginclude <conio.h>
int Fact (int);
int main()
{
int n, £, i;
float result=0.0;
WI) + 1/21 + 1/31
elrecr();
printf ("\n Bnter the value of n: *);
ecanf ("%d", &n);
for (iel; i<en; ies)
i
f-Fact (i);
result *= 1/(float)f;
}
printf("\n The sum of the series 1/1! 4
if2t ¢ if3t...
getch();
return 0;
= %.1£", result);
}
int Fact (int num)
{
int fel, i;
for (ienum; i>=1;i--)
£ = €*i;
return f;
Output
Enter the value of n: 2
The sum of the series 1/1!
2f/80l.4 «2.8
+1 /2r"y
9. Write a program to sum the series—1/1! + 4/2! +
7173! + _.
#include <stdio.h>
#include <conio.h>
#include <math.h>
int Fact (int);
int main()
{
int n, i, NUM, DENO;
float sum=0.0;
clrscr() ;
printf("\n Enter the value of n");
scanf ("%d", &n);
for (i=1; i<=n; i++)
{
NUM = pow(i,i);
DEMO = Fact (i);
sum += (float) NUM/DENO;
printf(*\n 1/1! + 4/2! + 27/3! + ...-5
%.2£*, sum);
getch();
Functions | 115]
return 0;
int Pact (int n)
{
int fel, 4;
for (ien;is-1l;i--)
f=f*i;
return f;
Output
Enter the value of n: 3
1/1) + 46/2) + 27/31 + ....2 7.50
4.8 SCOPE OF VARIABLES
In C, all constants and variables have a defined scope.
By scope we mean the accessibility and visibility of the
variables at different points in the program. A variable or
a constant in C has four types of scope: block, function,
program, and file.
4.8.1 Block Scope
We have studied that a statement block is a group of
statements enclosed within opening and closing curly
brackets ({ }). Ifa variable is declared within a statement
block then as soon as the control exits that block, the
variable will cease to exist. Such a variable also known as
a local variable is said to have a block scope.
So far we had been using local variables. For example,
if we declare an integer x inside
Programming Tip: @ function, then that variable is
It is an error to unknown to the rest of the program
use the name of a (i.e., outside that function).
function argument Blocks of statements may be
as the name of a placed one after the other in a
local variable. program; such blocks that are
placed at the same level are
known as parallel blocks. However, a program may also
contain a nested block, like a while loop inside main (). If
an integer x is declared and initialized in main () , and then
re-declared and re-initialized in a while loop, then the
integer variable x will occupy different memory slots and
will be considered as different variables. The following
code reveals this concept:
#include <stdio.h>
int main()
{
int x = 10;
int i=0;
printf ("\n The value of x outside the
while loop is %d", x);