Storage and Recursion

Concept of Storage

The storage class of a variable determines its scope, storage duration, and linkage. A storage class in C is used to describe the following things:

  • The variable scope
  • The location where the variable will be stored
  • Initialized value of a variable
  • A lifetime of a variable

There are four storage classes in the C language:

  • Automatic
  • External
  • Static
  • Register

List of storage classes and the keyword

Storage Classes Keyword
Automatic auto
External extern
Static static
Register register

Automatic Storage Class

All variables are declared within a function body. It has a features like:

  • Automatic variables are truly local.
  • They are unknown to other functions.
  • When the function is exited, the values of automatic variables are not retained.
  • They are normally implemented using a stack.
  • They are recreated each time the function is called.
  • It’s an optional to put the class specifier auto while declaring automatic variable.
#include<stdio.h>  
#include<conio.h>  
void main()  
{  
auto int a,b;  
 clrscr();  
 printf("The value of a= %d and b=%d", a,b);  
 getch();  
}  

Output:
The value of a = -28762 and b = 12803

External Storage Class (Global variable)

Variables are declared outside function. It has features like:

  • They are declared outisde the function.
  • All functions in the program can access and modify global variables.
  • The life-time of the variable is as long as the program’s execution does not come to an end.
  • The default initial value for this variable is zero.
  • An external variable must begin with the class specifier extern.
#include<stdio.h>  
#include <conio.h>  
extern int a=5, b=6;  
int sum()  
{  
int s;  
 s= a+b;  
return(s);  
}  
void main()  
{  
 clrscr();  
 printf("The sum is %d", sum());  
 getch();  
}  

Output:
The sum is 11

Concept of Recursion

The process in which a function calls itself is called recursion and the corresponding function is called a recursive function.

C program to input a number and calculate its factorial using recursive function.
#include<stdio.h>  
#include<conio.h>  
int factorial (int);  
void main()  
{  
int n, fact;  
  printf("Input a number:");  
  scanf("%d", &n);  
  fact=factorial(n);  
  printf("The factorial of %d is %d", n, fact);  
  getch();  
}  
int factorial(int n)  
{  
if(n==0 || n==1) return 1;  
else  
return (n*factorial(n-1));  
}  

Output:
Input a number: 5
The factorial of 5 is 120

A program to calculate the nth term of a Fibonacci series using recursive function.
#include<stdio.h>  
#include<conio.h>  
int fibo(int);  
void main()  
{  
int n, fact;  
  printf("Input the value of n:");  
 scanf("%d", &n);  
 fact=fibo(n);  
 printf("The value of nth term= %d",fact);  
 getch();  
}  
fibo(int n)  
{  
if(n==1)  
return(0);  
else if(n==2)  
return(1);  
else  
return(fibo(n-1)+fibo(n-2));  
}  

Output:
Input the value of n: 7
The value of nth term=8