You are on page 1of 26

Arrays

Overview
• An array is a collection of data items, all of the same type, accessed using a common
name.
• A one-dimensional array is like a list; A two dimensional array is like a table; The C
language places no limits on the number of dimensions in an array, though specific
implementations may required.
• Some texts refer to one-dimensional arrays as vectors, two-dimensional arrays
as matrices, and use the general term arrays when the number of dimensions is
unspecified or unimportant.

An array is a data structure that holds a number of related variables. Thus, an array has
a size which is the number of variables it can store. All of these variables must be of the
same type. (In essence declaring an array allows you to use many variables of the same
type without explicitly declaring all of them.)

Declaring Arrays

• Array variables are declared identically to variables of their data type, except
that the variable name is followed by one pair of square [ ] brackets for each
dimension of the array.
• Uninitialized arrays must have the dimensions of their rows, columns, etc.
listed within the square brackets.
• Dimensions used when declaring arrays in C must be positive integral
constants or constant expressions.

To declare an array called values that contains 5 floating point elements, you would
use
float values[5];

This declaration requires that your program statically allocate a total of 20 bytes of
memory (5 floats × 4 bytes/float = 20 bytes) at runtime. You can also initialize arrays
to contain given values, such as
float values[] = {1,2,3,4,5};

Example 1: Create an array to store Roll numbers of 50 students.

Compiled by BirodhRijal, Lecturer IOE Pulchowk Campus Page 1

N.S.U
Since Roll Number takes whole number integer. The declaration would be:

introll_number[50];

The above statement creates 50 memory slots to store 50 integer values.

Example 2: Initialize an array with set of number that represent percentage of 10


students.

{55.5,67.0,75.9,68.8,82.7,78.0,75.0,85.2,87.5,80.8}

Since the percentage can be any whole number or decimal point number so we choose
floating point type array and each elements are initialized by assigning the set with the
array declaration.

float percentage[] ={55.5,67.0,75.9,68.8,82.7,78.0,75.0,85.2,87.5,80.8};

Here we have not provided the size of array in the declaration because we have
initialized the elements during declaration so it automatically reserves memory by
counting the number of items that are included in the declaration.

Each cell of the array can hold one data item. Furthermore, each cell has its own
index, to distinguish it from the rest of the cells. In C, these cells are always
numbered from 0 to the size of the array minus one.

Using Arrays
• Elements of an array are accessed by specifying the index ( offset ) of the desired
element within square [ ] brackets after the array name.
• Array subscripts must be of integer type. ( int, long int, char, etc. )
• VERY IMPORTANT: Array indices start at zero in C, and go to one less than the
size of the array. For example, a five element array will have indices zero through
four. This is because the index in C is actually an offset from the beginning of the
array. ( The first element is at the beginning of the array, and hence has zero
offset. )
• Arrays are commonly used in conjunction with loops, in order to perform the
same calculations on all ( or some part ) of the data items in the array.

Compiled by BirodhRijal, Lecturer IOE Pulchowk Campus Page 2

N.S.U
Sample Programs Using 1-D Arrays
• This program uses loops and arrays to calculate the first twenty Fibonacci
numbers. Fibonacci numbers are used to determine the sample points used in
certain optimization methods.
/* Program to calculate the first 20 Fibonacci numbers. */

#include <stdlib.h>
#include <stdio.h>

int main( void )


{
inti, fibonacci[20];

fibonacci[0] = 0;
fibonacci[1] = 1;

for( i = 2; i< 20; i++ )


fibonacci[i] = fibonacci[i - 2]+ fibonacci[i-1];

for( i = 0; i< 20; i++ )


printf( "Fibonacci[%d] = %f\n", i,fibonacci[i]);

}/* End of program to calculate Fibonacci numbers */

The following program will read in five test scores and then print these out in reverse
order:
#include <stdlib.h>
#include <stdio.h>
int main()

int index, test_scores[5];


printf("Please enter 5 test scores.\n");
for (index=0; index < 5; index++)
scanf("%d", &test_scores[index]);
printf("Here are the scores in reverse order: ");
for (index=4; index >= 0; index--)
printf("%d ", test_scores[index]);
}

Compiled by BirodhRijal, Lecturer IOE Pulchowk Campus Page 3

N.S.U
Common mistakes made with arrays
1. Out of Bounds error: This is when you index into an array with an invalid index. For
example, if you declare an array as follows:
inttest_scores[5];

and tried to access test_scores[5] or test_scores[-1], you would be trying to access a variable
that does not exist, since the valid indeces of test_scores range from 0 through 4.

2. Not initializing all values of an array.


3. Trying to assign an entire array a value such as:

test_scores = 7;

This will not assign 7 to each element of the array test-scores. In fact, it is not syntactically
correct. This is because the left-hand side is not an integer variable, while the right hand
side is an integer expression.

• Exercise: What is the output of the following program (Try it yourself)


/* Sample Program Using Arrays */

#include <stdlib.h>
#include <stdio.h>

int main( void ) {

int numbers[ 10 ];
inti, index = 2;

for( i = 0; i< 10; i++ )


numbers[ i ] = i * 10;

numbers[ 8 ] = 25;
numbers[ 5 ] = numbers[ 9 ] / 3;
numbers[ 4 ] += numbers[ 2 ] / numbers[ 1 ];
numbers[ index ] = 5;
++numbers[ index ];
numbers[ numbers[ index++ ] ] = 100;
numbers[index] = numbers[numbers[index + 1]/7 ]--;

for( index = 0; index < 10; index++ )


printf("numbers[%d] = %d\n" index,numbers[index] );

} /* End of the program */

Compiled by BirodhRijal, Lecturer IOE Pulchowk Campus Page 4

N.S.U
Multidimensional Arrays

• Multi-dimensional arrays are declared by providing more than one set of square
[ ] brackets after the variable name in the declaration statement.
• One dimensional arrays do not require the dimension to be given if the array is to
be completely initialized. By analogy, multi-dimensional arrays do not
require the first dimension to be given if the array is to be completely initialized.
All dimensions after the first must be given in any case.
• For two dimensional arrays, the first dimension is commonly considered to be the
number of rows, and the second dimension the number of columns
• Two dimensional arrays are considered by C to be an array of ( single dimensional
arrays ). For example, "int numbers[ 5 ][ 6 ]" would refer to a single dimensional
array of 5 elements.
• Multidimensional arrays may be completely initialized by listing all data elements
within a single pair of curly {} braces, as with single dimensional arrays.
• It is better programming practice to enclose each row within a separate subset of
curly {} braces, to make the program more readable

For example:

Int x[][3]={ {6,12,92},{12,23,45}};

Here each subset inside curly braces represents a row and each elements in the
subset represent the column value.

• Multidimensional arrays may be partially initialized by not providing complete


initialization data. Individual rows of a multidimensional array may be partially
initialized, provided that subset braces are used.

Compiled by BirodhRijal, Lecturer IOE Pulchowk Campus Page 5

N.S.U
Sample Program Using 2-D Arrays
/* Sample program Using 2-D Arrays */

#include <stdlib.h>
#include <stdio.h>

int main( void ) {

/* Program to add two multidimensional arrays */

int a[ 2 ][ 3 ] = { { 5, 6, 7 }, { 10, 20, 30 } };


int b[ 2 ][ 3 ] = { { 1, 2, 3 }, { 3, 2, 1 } };
int sum[ 2 ][ 3 ], row, column;

/* First the addition */

for( row = 0; row < 2; row++ )


for( column = 0; column < 3; column++ )
sum[ row ][ column ] =
a[ row ][ column ] + b[ row ][ column ];

/* Then print the results */

printf( "The sum is: \n\n" );

for( row = 0; row < 2; row++ ) {


for( column = 0; column < 3; column++ )
printf( "\t%d", sum[ row ][ column ] );
printf( '\n' ); /* at end of each row */
}

return 0;
}

To declare multidimensional arrays , you would use


float values[5][3];
and you can access these values in a similar manner with

for(i=0;i<5;i++)
{
for(j=0;j<3;j++)\
{
printf(‘‘%f\n’’,values[i][j]);

Compiled by BirodhRijal, Lecturer IOE Pulchowk Campus Page 6

N.S.U
Strings
The string in C programming language is actually a one-dimensional array of characters which is
terminated by a null character '\0'. Thus a null-terminated string contains the characters that
comprise the string followed by a null.

The following declaration and initialization create a string consisting of the word "Hello". To
hold the null character at the end of the array, the size of the character array containing the
string is one more than the number of characters in the word "Hello."

char greeting[6]={'H','e','l','l','o','\0'};

If you follow the rule of array initialization then you can write the above statement as follows:

char greeting[]="Hello";

Following is the memory presentation of above defined string in C/C++:

Actually, you do not place the null character at the end of a string constant. The C compiler
automatically places the '\0' at the end of the string when it initializes the array. Let us try to
print above mentioned string:
#include<stdio.h>

int main ()
{
char greeting[6]={'H','e','l','l','o','\0'};

printf("Greeting message: %s\n", greeting );

return0;
}

When the above code is compiled and executed, it produces result something as follows:

Greeting message: Hello

Compiled by BirodhRijal, Lecturer IOE Pulchowk Campus Page 7

N.S.U
string.h
The string-handling functions are implemented in libraries. String I/O operations are
implemented in <stdio.h> (puts , gets, etc). A set of simple string manipulation functions are
implemented in <string.h>.
The string library (string.h) has some useful functions for working with strings, like strcpy,
strcat, strcmp, strlen, strcoll, etc. We will take a look at some of these string operations.

gets() and puts()


Functions gets() and puts() are two string functions to take string input from user and
display string respectively as mentioned in previous chapter.

#include<stdio.h>
int main ()
{
char name[30];
printf("Enter name: ");
gets(name);//Function to read string from user.
printf("Name: ");
puts(name);//Function to display string.
return0;
}

Though, gets() and puts() function handle string, both these functions are defined
in "stdio.h" header file.

Important: Don’t forget to include the library string.h (or on some systems strings.h) if you
want to use one of these library functions.
strcpy
This library function is used to copy a string and can be used like this: strcpy(destination,
source). (It is not possible in C to do this: string1 = string2). Take a look at the following
example:

charstr_one[] = "abc";
charstr_two[] = "def";
strcpy(str_one , str_two); // str_one becomes "def"

Note: strcpy() will not perform any boundary checking, and thus there is a risk of overrunning the
strings.

Compiled by BirodhRijal, Lecturer IOE Pulchowk Campus Page 8

N.S.U
strcmp(string 1, string2):
This library function is used to compare two strings and can be used like this: strcmp(str1,
str2).

 If the first string is greater than the second string a number greater than null (0) is
returned.
 If the first string is less than the second string a number less than null is returned.
 If the first and the second string are equal a null is returned.
Take look at an example:

printf("Enter you name: ");


scanf("%s", name);
if( strcmp( name, "jane" ) == 0 )
printf("Hello, jane!\n");

Note: strcmp() will not perform any boundary checking, and thus there is a risk of overrunning
the strings.

strcmpi (string 1, string2):This function is similar to strcmp().The only difference is that it ignores
the case.

Example
#include <stdio.h>
#include <string.h>
void main(void)
{
char string1[]="spark",string2[]="SPArk";
intcmp;
cmp=strcmpi(string1,string2);
if(cmp>0)
printf("%s > %s",string1,string2);
else
{
if(cmp<0)
printf("%s < %s",string1,string2);
else
printf("%s = %s",string1,string2);
}
}

Output: spark = SPArk.

Compiled by BirodhRijal, Lecturer IOE Pulchowk Campus Page 9

N.S.U
strcat
This library function concatenates a string onto the end of the other string. The result is
returned. Take a look at the example:

printf("Enter you age: ");


scanf("%s", age);
result = strcat( age, " years old.");
printf("You are %s\n", result);

Note: strcat() will not perform any boundary checking, and thus there is a risk of
overrunning the strings.
strlen
This library function returns the length of a string. (All characters before the null
termination.) Take a look at the example:

char name= "jane";


result = strlen(name); //Will return size of four.
scanf("%s", age);

Example:Program to sort n names in alphabetical order


#include<stdio.h>
#include<string.h>
voidmain()
{
char s[50][20],t[20];
inti,j,n;
printf(“how many names: “);
scanf(“%d”,&n);
printf("Enter %d strings : ",n);
for(i=0;i<n;i++)
scanf("%s",s[i]);

for(i=1;i<n;i++)
{
for(j=1;j<n;j++)
{
if(strcmp(s[j-1],s[j])>0)
{
strcpy(t,s[j-1]);
strcpy(s[j-1],s[j]);

Compiled by BirodhRijal, Lecturer IOE Pulchowk Campus Page 10

N.S.U
strcpy(s[j],t);
}
}
}

printf("Strings in order are : ");


for(i=0;i<5;i++)
printf("n%s",s[i]);
getch();
}

Compiled by BirodhRijal, Lecturer IOE Pulchowk Campus Page 11

N.S.U
Function
A function is a group of statements that together perform a task. Every C program has at least
one function, which is main(), and all the most trivial programs can define additional functions.

You can divide up your code into separate functions. How you divide up your code among
different functions is up to you, but logically the division usually is so each function performs a
specific task.

A function declaration tells the compiler about a function's name, return type, and parameters.
A function definition provides the actual body of the function.
The C standard library provides numerous built-in functions that your program can call. For
example, function scanf() to scan the input from keyboard, function memcpy() to copy one
memory location to another location and many more functions.

A function is also termed with various names like a method or a sub-routine or a procedure,
etc.

Defining a Function:
The general form of a function definition in C programming language is as follows:

return_typefunction_name( parameter list )


{
body of the function
}

A function definition in C programming language consists of a function header and a function


body. Here are all the parts of a function:

• Return Type: A function may return a value. The return_type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In
this case, the return_type is the keyword void.
• Function Name: This is the actual name of the function. The function name and the parameter
list together constitute the function signature.
• Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to
the parameter. This value is referred to as actual parameter or argument. The parameter list
refers to the type, order, and number of the parameters of a function. Parameters are optional;
that is, a function may contain no parameters.
• Function Body: The function body contains a collection of statements that define what the
function does.
int max(int num1,int num2)
{
}

Compiled by BirodhRijal, Lecturer IOE Pulchowk Campus Page 12

N.S.U
Hereintis the return type, max is the function name and the parameters are int num1and
int num2. Parameter consists of data type and variable name. Each parameter are
separated with comma in function header.
Example:
Following is the source code for a function called max(). This function takes two parameters
num1 and num2 and returns the maximum between the two:
/* function returning the max between two numbers */
int max(int num1,int num2)
{
/* local variable declaration */
int result;

if(num1 > num2)


result= num1;
else
result= num2;

return result;
}

Function Declarations:
A function declaration tells the compiler about a function name and how to call the function.
The actual body of the function can be defined separately.

A function declaration has the following parts:

return_typefunction_name( parameter list );

For the above defined function max(), following is the function declaration:

int max(int num1,int num2);

Parameter names are not important in function declaration only their type is required, so
following is also valid declaration:

int max(int,int);

Function declaration is required when you define a function in one source file and you call that
function in another file. In such case you should declare the function at the top of the file calling
the function.

Compiled by BirodhRijal, Lecturer IOE Pulchowk Campus Page 13

N.S.U
Calling a Function:
While creating a C function, you give a definition of what the function has to do. To use a
function, you will have to call that function to perform the defined task.

When a program calls a function, program control is transferred to the called function. A called
function performs defined task and when its return statement is executed or when its function-
ending closing brace is reached, it returns program control back to the main program.

To call a function, you simply need to pass the required parameters along with function name,
and if function returns a value, then you can store returned value. For example:

#include<stdio.h>

/* function declaration */
int max(int num1,int num2);

int main ()
{
/* local variable definition */
int a =100;
int b =200;
int ret;

/* calling a function to get max value */


ret= max(a, b);

printf("Max value is : %d\n", ret );

return0;
}

/* function returning the max between two numbers */


int max(int num1,int num2)
{
/* local variable declaration */
int result;
if(num1 > num2)
result= num1;
else
result= num2;
return result;
}

Compiled by BirodhRijal, Lecturer IOE Pulchowk Campus Page 14

N.S.U
I kept max() function along with main() function and compiled the source code. While running
final executable, it would produce the following result:

Max value is : 200


Simple example program for C function:

• As you know, functions should be declared and defined before calling in a C program.
• In the below program, function “square” is called from main function.
• The value of “m” is passed as argument to the function “square”. This value is multiplied
by itself in this function and multiplied value “p” is returned to main function from
function “square”.
#include<stdio.h>
/* function prototype, also called function
declaration*/
float square ( float x );

/* main function, program starts from here*/


int main( )
{

float m, n ;
printf ( "\nEnter some number for finding square \n");
scanf ( "%f", &m ) ;
n = square ( m ) ; /* function call*/
printf ( "\nSquare of the given number %f is %f",m,n );

}
/* function definition starts form here*/
float square ( float x )
{
float p ;
p = x * x ;
return ( p ) ;
}

Function Arguments:
Argument: An argument is an expression which is passed to a function by its in order for the
functionto perform its task. It is an expression in the comma-separated list bound by the
parentheses in a function call expression.

Compiled by BirodhRijal, Lecturer IOE Pulchowk Campus Page 15

N.S.U
Actual arguments:

The arguments that are passed in a function call are called actual arguments. These arguments
are defined in the calling function.

Formal arguments:
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
The formal arguments are the parameters/arguments in a function definition. The scope of
formal arguments is local to the function definition in which they are used. Formal arguments
belong to the called function. Formal arguments are a copy of the actual arguments. A change
in formal arguments would not be reflected in the actual arguments.

The formal parameters behave like other local variables inside the function and are created
upon entry into the function and destroyed upon exit.

Example
#include <stdio.h>
#include<conio.h>
void sum(int x, int y)
{
int z;
z=x+y;
printf(“\n Sum =%d”,z);
}
int main()
{
inta,b,c;
a=10;
b=20;
c=sum(a,b);
getch();
return 0;
}
Here int x, int y which are used as arguments in function definition are formal
arguments and a,b which are used in the calling portion of the program are actual arguments.

While calling a function, there are two ways that arguments can be passed to a function:

Compiled by BirodhRijal, Lecturer IOE Pulchowk Campus Page 16

N.S.U
Call Type Description
This method copies the actual value of an argument into the
formal parameter of the function. In this case, changes
Call by value
made to the parameter inside the function have no effect
on the argument.
This method copies the address of an argument into the
formal parameter. Inside the function, the address is used
Call by reference
to access the actual argument used in the call. This means
that changes made to the parameter affect the argument.

By default, C uses call by value to pass arguments. In general, this means that code within a
function cannot alter the arguments used to call the function and above mentioned example
while calling max() function used the same method.

Types of functions :
There are 2(two) types of functions as:
1. Built in Functions
2. User Defined Functions

1. Built in Functions :

These functions are also called as 'library functions'. These functions are provided by system.
These functions are stored in library files. e.g.
• scanf()
• printf()
• strcpy()
• strcmp()
• strlen()
• strcat()

2. User Defined Functions :

The functions which are created by user for program are known as 'User defined functions'.
User can give any name to the function which they want to create. The code to perform specific
task by the function are enclosed inside the body of function definition. The following program
demonstrate the use of user defined function in the program.

Compiled by BirodhRijal, Lecturer IOE Pulchowk Campus Page 17

N.S.U
Program :
/* Program to demonstrate function. */

#include <stdio.h>
#include <conio.h>

void add()
{
int a, b, c;
clrscr();
printf("\n Enter Any 2 Numbers : ");
scanf("%d %d",&a,&b);
c = a + b;
printf("\n Addition is : %d",c);
}
void main()
{
void add();
add();
getch();
}
Passing Arrays as Function Arguments in C
If you want to pass a single-dimension array as an argument in a function, you would have to
declare function formal parameter in one of following ways and all three declaration methods
produce similar results because each tells the compiler that an integer pointer is going to be
received. Similar way you can pass multi-dimensional array as formal parameters.

Way-1
Formal parameters as a sized array as follows:

voidmyFunction(intparam[])
{
.
.
.
.
}

Compiled by BirodhRijal, Lecturer IOE Pulchowk Campus Page 18

N.S.U
Way-2
Formal parameters as a pointer as follows.

voidmyFunction(int*param)
{
/*function body*/
}

Example
Now, consider the following function, which will take an array as an argument along with
another argument and based on the passed arguments, it will return average of the numbers
passed through the array as follows:

#include<stdio.h>
/* function declaration */
doublegetAverage(intarr[],int size);
int main ()
{
/* an int array with 5 elements */
int balance[5]={1000,2,3,17,50};
doubleavg;
/* pass pointer to the array as an argument */
avg=getAverage( balance,5);

/* output the returned value */


printf("Average value is: %f ",avg);

return0;

}
doublegetAverage(intarr[],int size)
{
inti;
doubleavg;
double sum;

for(i=0;i< size;++i)
{
sum+=arr[i];
}
avg= sum / size;
returnavg;
}

Compiled by BirodhRijal, Lecturer IOE Pulchowk Campus Page 19

N.S.U
C – Argument & return value
All C functions can be called either with arguments or without arguments in a C program.
These functions may or may not return values to the calling function.

1. C function with arguments (parameters) and with return value


2. C function with arguments (parameters) and without return value
3. C function without arguments (parameters) and without return value
4. C function without arguments (parameters) and with return value

Note:

• If the return data type of a function is “void”, then, it can’t return any values to the
calling function.
• If the return data type of the function is other than void such as “int, float, double etc”,
then, it can return values to the calling function.

1. Example program for with arguments & with return value:


In this program, integer, array and string are passed as arguments to the function. The return
type of this function is “int” and value of the variable “a” is returned from the function. The
values for array and string are modified inside the function itself.

#include<stdio.h>
#include<string.h>
int function(int, int[], char[]);
int main()
{
inti, a = 20;
intarr[5] = {10,20,30,40,50};
charstr[30] = "\"fresh2refresh\"";

printf(" ***values before modification***\n");


printf("value of a is %d\n",a);

for (i=0;i<5;i++)
{
// Accessing each variable
printf("value of arr[%d] is %d\n",i,arr[i]);
}
printf("value of str is %s\n",str);

printf("\n ***values after modification***\n");

a= function(a, &arr[0], &str[0]);

printf("value of a is %d\n",a);

Compiled by BirodhRijal, Lecturer IOE Pulchowk Campus Page 20

N.S.U
for (i=0;i<5;i++)
{
// Accessing each variable
printf("value of arr[%d] is %d\n",i,arr[i]);
}
printf("value of str is %s\n",str);

return 0;
}

int function(int a, int *arr, char *str)


{
inti;

a = a+20;
arr[0] = arr[0]+50;
arr[1] = arr[1]+50;
arr[2] = arr[2]+50;
arr[3] = arr[3]+50;
arr[4] = arr[4]+50;
strcpy(str,"\"modified string\"");

return a;

2. Example program for with arguments & without return value:

In this program, integer, array and string are passed as arguments to the function. The return
type of this function is “void” and no values can be returned from the function. All the values of
integer, array and string are manipulated and displayed inside the function itself.

#include<stdio.h>

void function(int, int[], char[]);

int main()
{
int a = 20;
intarr[5] = {10,20,30,40,50};
charstr[30] = "\"fresh2refresh\"";

function(a, &arr[0], &str[0]);


return 0;
}

void function(int a, int *arr, char *str)


{
Int i;

Compiled by BirodhRijal, Lecturer IOE Pulchowk Campus Page 21

N.S.U
printf("value of a is %d\n\n",a);

for (i=0;i<5;i++)
{
// Accessing each variable
printf("value of arr[%d] is %d\n",i,arr[i]);
}
printf("\nvalue of str is %s\n",str);
}

3. Example program for without arguments & without return value:

In this program, no values are passed to the function “test” and no values are returned from
this function to main function.

#include<stdio.h>
#include<conio.h>

void test();

int main()
{
test();
getch();
return 0;
}

void test()
{
int a = 50, b = 80;
printf("\nvalues : a = %d and b = %d", a, b);
}

4. Example program for without arguments & with return value:

In this program, no arguments are passed to the function “sum”. But, values are returned
from this function to main function. Values of the variable a and b are summed up in the
function “sum” and the sum of these value is returned to the main function.

#include<stdio.h>
int sum();
int main()
{
int addition;
addition = sum();
printf("\nSum of two given values = %d", addition);
return 0;
}

int sum()

Compiled by BirodhRijal, Lecturer IOE Pulchowk Campus Page 22

N.S.U
{
int a = 50, b = 80, sum;

sum = a + b;
return sum;
}

Storage Class
'Storage' refers to the scope of a variable and memory allocated by compiler to store that
variable. Scope of a variable is the boundary within which a varible can be used. Storage class
defines the the scope and lifetime of a variable.
From the point view of C compiler, a variable name identifies physical location from a computer
where varaible is stored. There are two memory locations in a computer system where
variables are stored as : Memory and CPU Registers.
Functions of storage class
To detemine the location of a variable where it is stored ?
Set initial value of a variable or if not specified then setting it to default value.
Defining scope of a variable.
To determine the life of a variable.

Types of Storage Classes :


Storage classes are categorised in 4 (four) types as,
• Automatic Storage Class
• Register Storage Class
• Static Storage Class
• External Storage Class

Automatic Storage Class :


o Keyword : auto
o Storage Location : Main memory
o Initial Value : Garbage Value
o Life : Control remains in a block where it is defined.
o Scope : Local to the block in which variable is declared.

Syntax :
auto [data_type] [variable_name];
Example :
autoint a;
/* Program to demonstrate automatic storage class.*/

#include <stdio.h>

Compiled by BirodhRijal, Lecturer IOE Pulchowk Campus Page 23

N.S.U
#include <conio.h>
void main()
{
autointi=10;
{
autointi=20;
printf("\n\t %d",i);
}
printf("\n\n\t %d",i);
getch();
}
Output
20
10
Register Storage Class :
o Keyword : register
o Storage Location : CPU Register
o Initial Value : Garbage
o Life : Local to the block in which variable is declared.
o Scope : Local to the block.
Syntax :
register [data_type] [variable_name];
Example :
registerint a;

Register variables occur in CPU and value of that register variable is stored in a register within
that CPU. Thus, it increases the resultant speed of operations. There is no waste of time, getting
variables from memory and sending it to back again.
It is not applicable for arrays, structures or pointers.

/* Program to demonstrate register storage class.*/


#include <stdio.h>
#include <conio.h>
void main()
{
registerinti=10;
clrscr();
{
registerinti=20;
printf("\n\t %d",i);
}
printf("\n\n\t %d",i);

Compiled by BirodhRijal, Lecturer IOE Pulchowk Campus Page 24

N.S.U
getch();
}

Static Storage Class :


o Keyword : static
o Storage Location : Main memory
o Initial Value : Zero and can be initialize once only.
o Life : depends on function calls and the whole application or program.
o Scope : Local to the block.
Syntax :
static [data_type] [variable_name];
Example :

staticint a;

Static storage class can be used only if we want the value of a variable to persist between
different function calls.

/* Program to demonstrate static storage class.*/


#include <stdio.h>
#include <conio.h>
void main()
{
inti;
voidincre(void);
clrscr();
for (i=0; i<3; i++)
incre();
getch();
}
voidincre(void)
{
intavar=1;
staticintsvar=1;
avar++;
svar++;
printf("\n\n Automatic variable value : %d",avar);
printf("\t Static variable value : %d",svar);
}

Output

Compiled by BirodhRijal, Lecturer IOE Pulchowk Campus Page 25

N.S.U
Automatic variable value : 2 Static variable value : 2
Automatic variable value : 2 Static variable value : 3
Automatic variable value : 2 Static variable value : 4 : 2 Static variable value : 2

External Storage Class :


o Keyword : extern
o Storage Location : Main memory
o Initial Value : Zero
o Life : Until the program ends.
o Scope : Global to the program.
Syntax :
extern [data_type] [variable_name];
Example :

externint a;

Compiled by BirodhRijal, Lecturer IOE Pulchowk Campus Page 26

N.S.U

You might also like