Showing posts with label 6. PROGRAM STRUCTURE. Show all posts
Showing posts with label 6. PROGRAM STRUCTURE. Show all posts

Thursday, December 17, 2009

6.4 STATIC VARIABLES

In this section and the next, we make the distinction between a single-file program,in which the entire program is contained within a single source file, and a multiple program,where the functions that make up the program are contained in separate source files.the rules governing the static storage class are different in each situation.

In a single-file program,static variables are defined within individual functions and therefore have the same scope as automatic variables;i.e. they are local to the functions in which they are defined.Unlike automatic variables,however,static variable retain their values throughout the life of the program.Thus,if a function is exited and then re-entered at a later time,the static variables defined within that function will retain their former values.This feature allows function to retain information permanently throughout the execution of a program.

Static variables are defined within a function in the same manner as automatic variables,except that the variable declaration must begin with the static storage-class designation.Static variables can be utilized within the function in the same manner as other variables.They cannot,however, be accessed outside of their defining function.

Initial values can be included in the static variable declarations.The rules associated with the assignment of these values are essentially the same as the rules associated with the initialization of external variables, even though the static variables are defined locally within a function.In particular-
1. The initial values must be expressed as constants, not expressions.
2. The  initial values are assigned to their respective variables at the beginning of program execution.The variables retain these values throughout the life of the program, unless different values are assigned during the course of the computation.
3. Zeroes will be assigned to all static variables whose declarations do not explicit initial values.Hence, static variables will always have assigned values.


Generating Fibonacci  Numbers The Fibonacci numbers form an interesting sequence in which each number is equal to the sum of the previous two numbers.In other words,

F3 =F2 + F1

Let us write a C program that generates the first n Fibonacci numbers, where n is value specified by the user.


/*program to calculate successive Fibonacci numbers*/


#include < stdio.h >

long int fibonacci  (int count);


main() 
{
int count, n;


printf ("How many Fibonacci numbers?");
scanf ("%d", &n);
printf ("\n");


for (count=1;count <= n;++count)
printf ("\ni= %2d F=%1d", count, fibonacci (count));


}


long int fibonacci (int count)


/*calculate a fibonacci number using the formulas F=1 for n < 3 and F3= F1+F2 for n >=3*/

{
 static long int f1=1, f2=1;
long int f;


f= (count < 3)? 1 : f1+f2;
f2=f1;
f1=f;
return (f);

}

You should understand that f1 and f2 are strictly local variables, even though they retain their values from one function call to another.

The output corresponding to a value of n=6 is shown below.As usual the user's response is underlined.

How many Fibonacci numbers? 6
i=1  F=1

i=2  F=1
i=3  F=2
i=4  F=3
i=5  F=5
i=6  F=8   

6.3 EXTERNAL (GLOBAL) VARIABLES

External variables,in contrast to automatic variables, are not confined to single functions.Their scope extends from the point the point of definition through the remainder of the program.They are often referred to as global variables.

Since external variables are recognized globally,they can be accessed from any function that falls within their scope.They retain their assigned values within this scope.

When working with external variables, we must distinguish between external variable definitions and external variable declarations.An external variable definition is written in the same manner as an ordinary variable declaration.It must appear outside of ,and usually before,the functions that access the external variables.An external variable definition will automatically allocate the required storage space for the external variables within the computer's memory.The assignment of initial values can be included within an external variable definition if desired.

An external variable declaration must begin with the storage class specifier extern. The name of the external variable and its data type must agree with the corresponding external variable definition that appears outside of the function. Storage space for external variables will not be allocated as a result of an external variable declaration.Moreover, an external variable declaration cannot include the assignment of initial values.These distinctions between an external variable definition and external variable declaration are very important.

Let us write a program that makes use of external variables to represent the total (cumulative) numbers of characters read, and the total number of lines.

/*read several lines of text and determine the average number of characters per line*/

#include <  stdio.h>


int sum=0;               /*total number of characters*/
int lines=0;              /*total number of lines*/


int linecount(void)


main()
{
int n;          /*number of chars in a given line*/
float avg;    /*average number of chars per line*/


printf("Enter the text below\n");


/*read a line of text and update the cumulative counters*/


while (n=linecount() > 0)  {
sum +=n;
++lines;

 }
avg=(float) sum/lines;
printf("\nAverage number of characters per line: %5.2f", avg);

}


/*read a line of text and count the number of characters*/


int linecount(void)
{
char line[80];
int count=0;
while((line[count]=getchar()) != '\n')
++count;
return (count);

}

Notice that sum and lines are external variables that represent the total (cumulative) number of characters read and the total number of lines,respectively.Both of these variables are assigned initial values of zero.These values are successively modified within main,as additional lines of text are read.

Finally, it should  be pointed  out that there are inherent dangers in the use of external variables, since an alteration in the value of an external variable within a function will be carried over into other parts of the program.

6.2 AUTOMATIC VARIABLES

Automatic variables are always declared within a function and are local to the function in which they are declared; that is,their scope is confined to that function.Automatic variables defined in different functions will therefore be independent of one another,even though they may have the same name.

Any variable declared within a function is interpreted as an automatic variable unless a different storage class specification is shown within within the declaration.This includes formal argument declarations.All of the variables in the programming examples encountered earlier have been automatic variables.

Since the location of the variable declarations within the program determines the automatic storage class, the keyword auto is not required at the beginning of each declaration.There is no harm in including an auto specifications within a declaration,though this is normally not done.

Consider once again the program mentioned in section 5.6 for calculating factorials.Within main, n is an automatic variable ,the formal argument n is also an automatic variable.

The storage class designation auto could have been included explicitly in the variable declarations if we had wished.Thus the program could have been written as follows.


/*calculate the factorial of an integer quantity using recursion*/


#include stdio.h


long int factorial (int n);     /*function prototype*/


main()
{
auto int n;
long int factorial (int n);


/*read in the integer quantity*/
printf ("n= ");
scanf ("%d", &n);

/*calculate and display the factorial*/

printf ("n!=%d\n", factorial(n));


}


long int factorial (auto int n)        /*calculate the factorial*/

{
if (n <= 1);
return(1);
else
return (n * factorial (n-1));

}

Either method is acceptable.As a rule, however, the auto designation is not included in variable or formal argument declarations,since this is the default storage class.Thus the program shown in 5.6 represents a more common programming style.

An automatic variable does not retain its value once control is transferred out of its defining function.There for any value assigned to an automatic variable within a function will be lost once the function is exited.

Wednesday, December 16, 2009

6.1 STORAGE CLASSES

There are two different ways to characterize variables: by data type,and by storage class.Data type refers to the type of information represented by a variable ,e.g. integer number,floating-point number,character etc.Storage class refers to the permanence of a variable,and its scope within the program,i.e. the portion of the program over which the variable is recognized.

There are four different storage class specifications in C: automatic,external,static and register.They are identified by the keywords auto,extern,static and register respectively.

The storage class associated with a variable can sometimes be established simply by the location of the variable declaration within the program.In other situations,however, the keyword that specifies a particular storage class must be placed at the beginning of the variable declaration.

Shown below are several typical variable declarations that include the specification of  a storage class.

auto int a,b,c;
extern float root1,root2;
static int count=0;
extern char star;