Programming in C - 101-120
Programming in C - 101-120
The general strategy is to consider one of the poles to be the origin, and
another to be the destination. The third pole will be used for intermediate
storage, thus allowing the disks to be moved without placing a larger disk
over a smaller one. Assume there are n disks, numbered from smallest to
largest as in Figure 5.1. If the disks are initially stacked on the left pole, the
problem of moving all n disks to the right pole can be stated in the following
recursive manner:
1. Move the top n-1 disks from the left pole to the center pole.
2. Move the nth disk( the largest disk) to the right pole.
3. Move the n-1 disks on the center pole to the right pole.
The problem can be solved for any value of n greater than 0(n=0 represents
a stopping condition).
In order to program this game, we first label the poles, so that the left pole is
represented as L, the center pole as C and the right pole as R. Let us refer
the individual poles with the char-type variables from, to and temp for the
origin, destination and temporary storage respectively.
Program 5.5: Recursive Program to solve Towers of Hanoi problem.
#include<stdio.h>
main()
{
void Recursive_Hanoi(int, char, char, char);
int n;
printf(“ Towers of Hanoi\n\n”);
printf(“ How many disks?”);
scanf(“%d”, &n);
printf(“\n”);
Recusrive_Hanoi(n, ‘L’, ‘R’, ‘C’);
}
void Recursive_Hanoi(int n, char from, char to, char temp)
{
/* Transfer n disks from one pole to another */
/* n= number of disks
from=origin
to=destination
temp=temporary storage */
Manipal University Jaipur Page No.: 101
Programming in C Unit 5
{
if(n>0){
/* move n-1 disks from origin to temporary */
Recursive_Hanoi(n-1, from, temp, to);
#include<stdio.h>
main()
{
int n=5;
int fun(int n);
printf(“%d\n”, fun(n));
}
int fun(int n)
{
if(n==0)
return 0;
else
return (n+fun(n-1));
}
can't see inside it (and the function inside can't see out). When you call a
function, you only have to know what it does, not how it does it. When you're
writing a function, you only have to know what it's supposed to do, and you
don't have to know why or under what circumstances its caller will be calling
it. (When designing a function, we should perhaps think about the callers
just enough to ensure that the function we're designing will be easy to call,
and that we aren't accidentally setting things up so that callers will have to
think about any internal details.)
Some functions may be hard to write (if they have a hard job to do, or if it's
hard to make them do it truly well), but that difficulty should be
compartmentalized along with the function itself. Once you've written a
“hard'' function, you should be able to sit back and relax and watch it do that
hard work on call from the rest of your program. It should be pleasant to
notice (in the ideal case) how much easier the rest of the program is to write,
now that the hard work can be deferred to this workhorse function.
(In fact, if a difficult-to-write function's interface is well-defined, you may be
able to get away with writing a quick-and-dirty version of the function first, so
that you can begin testing the rest of the program, and then go back later
and rewrite the function to do the hard parts. As long as the function's
original interface anticipated the hard parts, you won't have to rewrite the
rest of the program when you fix the function.)
The functions are important for far more important reasons than just saving
typing. Sometimes, we'll write a function which we only call once, just
because breaking it out into a function makes things clearer and easier.
If you find that difficulties pervade a program, that the hard parts can't be
buried inside black-box functions and then forgotten about; if you find that
there are hard parts which involve complicated interactions among multiple
functions, then the program probably needs redesigning.
For the purposes of explanation, we've been seeming to talk so far only
about “main programs'' and the functions they call and the rationale behind
moving some piece of code down out of a “main program'' into a function.
But in reality, there's obviously no need to restrict ourselves to a two-tier
scheme. Any function we find ourselves writing will often be appropriately
written in terms of sub-functions, sub-sub-functions, etc.
5.6 Summary
A function is a self-contained program segment that carries out some
specific, well-defined task. When you find that a program is hard to manage,
it's often because it has not been designed and broken up into functions
Manipal University Jaipur Page No.: 105
Programming in C Unit 5
cleanly. A function is a “black box'' that we've locked part of our program into.
The idea behind a function is that it compartmentalizes part of the program.
The function main() is must in every C program. The function prototype is
nothing but the function declaration. Recursion is a process by which a
function calls itself repeatedly, until some specified condition has been met.
5. fib(i)= { 0 if i=1
1 if i=2
fib(i-1)+fib(i-2) otherwise}
6. Square of the integers from 1 to 10 is displayed.
5.10 Exercises
1. Suppose function F1 calls function F2 within a C program. Does the
order of function definitions make any difference? Explain.
2. When a program containing recursive function calls is executed, how are
the local variables within the recursive function interpreted?
3. Express the following algebraic formula in a recursive form:
Y = (x1+x2+…+xn)
4. Write a function that will allow a floating point number to be raised to an
integer power.
5. Write a function to swap two numbers using pass by value technique.
What is the drawback of the function?
6.1 Introduction
In the previous unit, you studied about functions. You found out that how
functions can be used to break the large problems into small problems and
then solve it. You studied how functions can be repeatedly called and used
again and again. In this unit, you will study about the types of storage
classes that are used in C. You will study how these storage classes are
useful in making the C language a very powerful computing language.
Variables are channels of communication within a program. You set a
variable to a value at one point in a program, and at another point (or points)
you read the value out again. The two points may be in adjoining statements,
or they may be in widely separated parts of the program. How long does a
variable last? How widely separated can the setting and fetching parts of the
program be, and how long after a variable is set does it persist? Depending
on the variable and how you're using it, you might want different answers to
these questions. For example, in some situations it may be desirable to
introduce certain “global” variables that are recognized throughout the entire
program (or within major portions of the program, e.g. two or more
functions). Such variables are defined differently than the usual “local”
variables, which are recognized only within a single function.
We will also consider the issue of static variables which can retain their
values, so that the function can be reentered later and the computation
resumed.
Finally, we may be required to develop a large, multifunction program in
terms of several independent files, with few functions defined within each file.
In such programs, the individual functions can be defined and accessed
locally within a single file, or globally within multiple files.
Objectives:
After studying this unit, you should be able to:
implement the concept of storage classes and visibility of variables
explain the difference between automatic variables, global variables,
static variables and external variables.
compile and execute a program made up of more than one source files.
{
auto int i; /* Here the keyword auto is optional */
auto long int factorial=1; /* Here the keyword auto is optional */
while(n>0)
{
factorial=factorial*n;
n=n-1;
}
return factorial;
}
An automatic variable doesn’t retain its value once control is transferred out
of its defining function. Therefore, any value assigned to an automatic
variable within a function will be lost once the function is exited.
Self Assessment Questions
4. The scope of an automatic variable is in ____________ in which it is
declared.
5. Does an automatic variable retain its value once control is transferred
out of its defining function? (Yes/No)
6. The key word auto is must in the declaration of automatic variables.
(True/False)
avg=cal_avg();
printf(“\nAverage number of characters per line: %5.2f”, avg);
}
void linecount(void)
{
/* read a line of text and count the number of characters */
char line[80];
int count=0;
while((line[count]=getchar())!=’\n’)
++count;
return count;
}
float cal_avg(void)
{
/* compute average and return*/
return (float)sum/lines;
}
In the above program the variables sum and lines are globally declared and
hence they could be used in both the functions main() and cal_avg()
{
/* external declarations of the variables which are defined in
externvariables.h */
extern int principle;
extern float rate;
extern int time;
extern float interest;
/*compute interest*/
interest= principle*rate*time/100.0;
printf(“Interest=%f\n”, interest);
}
Compile demoexternvar.c and execute the program.
The concept of external storage class can be extended to functions also. A
source file can access a function defined in any other source file provided
the source file is included within the source file where you access that
function.
Program 6.5: Program to illustrate the concept of external functions.
Type and save the following program in a file externfunction.h
void output(void)
{
printf(“ Hi, Manipal!\n”);
return;
}
Type and save the following program in a separate source file called
demoexternfun.c
#include<stdio.h>
#include “ externfunction.h”
extern void output(void);
main()
{
output();
}
Compile and execute the above program and observe the result.
However, the keyword extern is optional in some C compilers.
localvar is a local variable within the function f(). It can be accessed only
within the function f(). (If any other part of the program declares a variable
named “localvar'', that variable will be distinct from the one we're looking at
here.) localvar is conceptually “created'' each time f() is called, and
disappears when f() returns. Any value which was stored in localvar last
time f() was running will be lost and will not be available next time f() is
called. Furthermore, since it has no explicit initializer, the value of localvar
will in general be garbage each time f() is called.
localvar2 is also local, and everything that we said about localvar applies
to it, except that since its declaration includes an explicit initializer, it will be
initialized to 2 each time f() is called.
Finally, persistentvar is again local to f(), but it does maintain its value
between calls to f(). It has static duration but no explicit initializer, so its
initial value will be 0.
The term declaration is a general one which encompasses defining
instances and external declarations; defining instances and external
declarations are two different kinds of declarations. Furthermore, either kind
of declaration suffices to inform the compiler of the name and type of a
particular variable (or function). If you have the defining instance of a global
variable in a source file, the rest of that source file can use that variable
without having to issue any external declarations. It's only in source files
where the defining instance hasn't been seen that you need external
declarations.
You will sometimes hear a defining instance referred to simply as a
“definition,'' and you will sometimes hear an external declaration referred to
simply as a “declaration.'' These usages are mildly ambiguous, in that you
can't tell out of context whether a “declaration'' is a generic declaration (that
might be a defining instance or an external declaration) or whether it's an
external declaration that specifically is not a defining instance. Similarly,
there are other constructions that can be called “definitions'' in C, namely
the definitions of preprocessor macros, structures, and typedefs etc.
6.7 Summary
Variables are channels of communication within a program. Storage class
refers to the persistence of a variable and its scope within the program, that
is, the portion of the program over which the variable is recognized. The
scope of a local or automatic variable is confined to the function where it is
defined. A global variable is potentially visible anywhere within the program
in which it is defined. Static variables retain their values throughout the life
of the program. As a result, if a function is exited and then reentered later,
the static variables defined within that function will retain their previous
values. The external variable declaration says the compiler that the global
variable will be used in this source file but defined in some other source file.