UNIT-III STORAGE CLASS
There are two different ways to characterize variables, by data type and by storage class.
Data types refer to the type of information represented by a variable, such as integer, float, char, etc.
Storage class refers to the permanence of the variable and its scope within the program. There are 4 different storage-class specifications in C: automatic, external, static and register:
they are identified by the keywords auto, extern, static and register.
The storage class associated with a variable can sometimes be established simply by the location of the variable declaration within the program.
The keyword that specifies a particular storage class must be placed at the beginning of the variable declaration.
Automatic variables:
Automatic variables are always declared within a function and are local to the function in which they are declared.
Automatic variables defined in different functions will therefore be independent of one another, even though they may have the same name.
Automatic variable are declared inside a function in which they are utilized. They are created when the function is called and destroyed automatically when the function is exited.
#include<stdio.h> #include<conio.h> void test(); main( ) { Clrscr(); test(); test(); test(); getch(); } void test() { auto int a =1; printf (“% d”,a); a=a+ 10; } Out put: 1 1 1 External variables
A variable that are accessed throughout the entire program are known as external or global variables
Once a variable has been declared as global, any function can use it and change its value. the subsequent functions can refer only that new value
#include<stdio.h> #include<conio.h> void test1(); void test2( ); extern int x=1; main( ) { clrscr( ); printf(“\n x=%d”,x); test1( ); test2( ); getch( ); } void test1( ) { x=x+10; printf(“\n x=%d”,x); } void test2( ) { x=x+20; printf(“\n x=%d”,x); } Output: x=1 x=11 x=31
The major difference between external and global variable is that a global variable may be initialized by default as ‘0’, but an external variable must be initialized with a value.
Static variables:
The storage class, static, similarly provides a lifetime over the entire program, however; it provides a way to limit the scope of such variables.
Static storage class is declared with the keyword static as the class specifier when the
variable is defined. These variables are automatically initialized to zero upon memory allocation just as external variables are. Static storage class can be specified for automatic as well as external variables.
Static automatic variables continue to exist even after the block in which they are defined
terminates. Thus, the value of a static variable in a function is retained between repeated function calls to the same function.
The scope of static automatic variables is identical to that of automatic variables, i.e. it is local to the block in which it is defined; however, the storage allocated becomes permanent for the duration of the program.
Static variables may be initialized in their declarations; however, the initializers must be constant expressions, and initialization is done only once at compile time when memory is allocated for the static variable.
#include<stdio.h> #include<conio.h> void test( ); main( ) { clrscr ( ); test( ); test( ); test( ); getch( ); } void test( ) { static int x=1; printf(“\n x=%d”,x); x=x+10; } Output: X=1 X=11 X=21
Register variables:
Register variables are a special case of automatic variables. Automatic variables are allocated storage in the memory of the computer; however, for most computers, accessing data in memory is considerably slower than processing in the CPU. These computers often have small amounts of storage within the CPU itself where data can be stored and accessed quickly. These storage cells are called registers.
A register variable provides a certain control over efficiency of program execution. Variables which are used repeatedly or whose access times are critical may be declared to be of storage class register.
A register variable is kept in machine’s register instead of memory. A register is must faster than a memory access.
Keeping the frequently accessed variable such as loop control variable in register will lead to faster execution of programs.
/* demonstrates register storage class*/ #include<stdio.h> void test (); main () { test(); test (); test (); } void test() {
register int a=1; printf( “% d”,a); a=a +10
)
Output : 1 1 1
ARRAYS:
An array is a collection of same data items that are stored in a single variable.
A specific element in an array is accessed by an index (also called subscript) after the array name and enclosed in brackets [ ].
The individual elements may be called as indexed elements or subscripted elements. Array index will be start from 0 to n-1.
X[0] X[1] X[2] …….
. X[n-1]
C supports several dimensions of arrays. 1. One-dimensional arrays.
2. Multi-dimensional arrays. Defining an Array:
A list of homogenous data items can be given one variable name using only one subscript is called One-dimensional arrays.
Arrays are defined in the same manner as ordinary variables, except that array name must be specified by size.
Data-type Arrayname[size];
Where the Data-type specifies the type of elements in the array and size specifies the maximum number of elements stored in the array.
Ex: int A[10];
This array ‘A’ contains 10 indexed elements from 0 to 9. They are represented in memory as given below.
A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9]
Processing an array: 1. Initialize arrays
We can initialize a one-dimensional array like any other data types, by enclosing the initializes values in braces, separated by commas.
Ex: int a[5]={11,22,33,44,55};
The above is represented in memory as,
If we initialize few values less than the array size, then the remaining elements will be initialized with zeros automatically.
Ex: int a[5]={11,22,33};
When the array size is not given, then the compiler will assign the size by the number of initializes. Ex: int a[ ]={11,22,33,44};
2. Read array elements from key board:
We can read values of array elements from keyboard by using scanf( ) function within a loop. Ex: int a[5];
for(i=0; i<5; i++) scanf(“ %d”, &a[i]);
3. Write array elements on to screen:
We can write the values of array elements on to screen by using printf( ) function within a loop. Ex: for(i=0; i<5; i++)
printf(“ %d”, &a[i]);
/*Find sum &average of an array*/ #include<stdio.h> #include<conio.h> int n=5; main( ) { int a[ ]={2,4,6,8,10};
/*Find sum &average of an array*/ #include<stdio.h> #include<conio.h> main( ) { int a[5],i,sum=0; float avg; clrscr( ); 11 22 33 44 55
A[0] A[1] A[2] A[3] A[4]
11 22 33 0 0
int i,sum=0; float avg; clrscr( ); for(i=0;i<n;i++) { sum=sum+a[i]; } avg=sum/(float)n;
printf(“\n sum of array=%d”,sum); printf(“\n Average =%f”,avg); getch();
}
Test data:
Sum of array=30 Average=6.00000
printf(“\n Enter 5 elements”); for(i=0;i<n;i++) { Scanf(“%d”,&a[i]); sum=sum+a[i]; } avg=sum/5.0;
printf(“\n sum of array=%d”,sum); printf(“\n Average =%f”,avg); getch(); } Test data: Enter 5 elements: 2 4 6 8 10 Sum of array=30 Average=6.00000 Passing Functions to Arrays:
To pass an array to a function, the array name must appear by itself, without brackets, as an actual argument within the function call.
The corresponding formal argument is declared a one-dimensional array, the array name is written with a pair of empty square brackets, and the size of array is not specified.
When an array is passed to a function, the values of the array elements are not passed to the function. Rather, the array name is the address of the first element. This address is assigned to the corresponding formal argument when the function is called. The formal argument therefore becomes a pointer to the first array element.
Arguments that are passed in this manner are said to be passed by reference. #include<stdio.h> #include<conio.h> void square(int b[ ]); main() { int a[5],i; clrscr( );
printf("\n Enter 5 elements:"); for(i=0;i<5;i++)
scanf("%d",&a[i]); square(a);
printf("\n The square values:"); for(i=0;i<5;i++)
printf("%d ",a[i]);
Test data:
Enter 5 elements: 2 4 6 8 10 The square values: 4 16 36 64 100
getch( ); } void square(int b[ ]) { int i; for(i=0;i<5;i++) b[i]=b[i]*b[i]; } Multi-dimensional arrays:
Multi-dimensional arrays are defined in the same manner as one-dimensional arrays, except that a separate pair of brackets is required for each subscript. Thus, a two-dimensional array will require two pairs of brackets; a three-dimensional array will require three pairs of brackets. A two-dimensional array is a table of data items, consisting of rows and columns. The first
dimension refers to the row size and second dimension refers to column size. The general form is as follows;
Data-type Arrayname[row size][column size]; Ex: int x[3][3]; this array ‘s’ contains 3 rows, 3 columns and 9 elements. They can be stored in memory as follows.
Col1 Col2 Col3
Row 1 X[0] [0] X[0] [1] X[0] [2] Row 2 X[1] [0] X[1] [1] X[1] [2] Row 3 X[2] [0] X[2[1] X[2] [2]
We can initialize a two-dimensional array like one-dimensional arrays, by enclosing the initializes values in braces and separated by commas.
int a[3][3]={1,2,3,4,5,6,7,8,9}; We can also initialize in row by row method also. int a[3][3]={ {1,2,3}, {4,5,6}, {7,8,9} };
If we initialize few values less than the array size, then the remaining elements will be initialized with zeros automatically.
int a[3][3]={1,2,3,4,5,7,8}; int a[3][3]={{1,2,3},{4,5},{7.8} };
1 2 3 4 5 6 7 8 9 1 2 3 4 5 7 8 0 0 1 2 3 4 5 0 7 8 0
We can print the two-dimensional arrays using two for loops Ex: for(i=0; i<3; i++)
for(j=0; j<3; j++) Printf(“%d”, a[i][j]);
We can read a two-dimensional array using scanf( ) function. Ex: for(i=0; i<3; i++)
for(j=0; j<3; j++) scanf(“%d”, &a[i][j]);
/* Read & print matrix elements*/ #include<stdio.h> #include<conio.h> main( ) { int a[3][3],i,j; clrscr();
printf(“\n Enter elements”); for(i=0; i<3; i++)
{
for(j=0;j<3;j++) scanf(“%d”,&a[i][j]); }
printf(“\n Matrix form \n”); for(i=0; i<3; i++)
{ for(j=0;j<3;j++) printf(“%d”,a[i][j]); printf(“\n”); } getch( ); } Test data Enter elements 2 4 6 3 6 9 2 4 8 Matrix form 2 4 6 3 6 9 2 4 8 /* unit matrix */ main( ) { int a[3][3]={ {1},{0,1},{0,0,1} }; int i,j; clrscr();
printf(“\n unit matrix elements \n”); for(i=0; i<3; i++)
{ for(j=0;j<3;j++) printf(“ %d”,a[i][j]); printf(“\n”); } getch(); } Test data
Unit matrix elements 1 0 0
0 1 0 0 0 1
#include<stdio.h> #include<conio.h>
void matadd(int a[][5],int b[][5]); int a[5][5],b[5][5],c[5][5];
int i,j,r1,c1,r2,c2; main()
{
clrscr();
printf("Enter first matrix size:"); scanf("%d%d",&r1,&c1);
printf("\nEnter second matrix size\n"); scanf("%d%d",&r2,&c2);
if((r1==r2)&c1==c2) {
printf("\n Enter %d elements\n",r1*c1); for(i=0;i<r1;i++) { for(j=0;j<c1;j++) scanf("%d",&a[i][j]); } printf("\nEnter %d elements\n",r2*c2); for(i=0;i<r2;i++) { for(j=0;j<r2;j++) scanf("%d",&b[i][j]); }
matadd(a,b); /* function calling */ printf("\n result matrix \n");
for(i=0;i<r1;i++) { for(j=0;j<c2;j++) printf("%d\t",c[i][j]); printf("\n"); } } else
printf("\n Addition is not possible"); getch();
}
/*function definition */
void matadd(int a[][5],int b[][5]) { for(i=0;i<r1;i++) { for(j=0;j<c2;j++) c[i][j]=a[i][j]+b[i][j]; } }
#include<stdio.h> #include<conio.h>
void matmul(int a[][5],int b[][5]); int a[5][5],b[5][5],c[5][5];
int i,j,k,r1,c1,r2,c2; main()
{x clrscr();
printf("Enter first matrix size:"); scanf("%d%d",&r1,&c1);
printf("\nEnter second matrix size\n"); scanf("%d%d",&r2,&c2);
if(r1==c2) {
printf("\n Enter %d elements\n",r1*c1); for(i=0;i<r1;i++) { for(j=0;j<c1;j++) scanf("%d",&a[i][j]); } printf("\nEnter %d elements\n",r2*c2); for(i=0;i<r2;i++) { for(j=0;j<r2;j++) scanf("%d",&b[i][j]); } matmul(a,b);
printf("\n result matrix \n"); for(i=0;i<r1;i++) { for(j=0;j<c2;j++) printf("%d\t",c[i][j]); printf("\n"); } } else
printf("\n multiplication is not possible"); getch();
}
void matmul(int a[][5],int b[][5]) { for(i=0;i<r1;i++) { for(j=0;j<c2;j++) { c[i][j]=0; for(k=0;k<c1;k++) Test data
c[i][j]=c[i][j]+a[i][k]*b[k][j]; }
} }
Array Techniques Array Order Reversal
Problem: Rearrange the elements in an array, so that they appear in reverse order. Algorithm development:
We can start the design of this algorithm by careful examination of the element of an array before and after it has been reversed.
1 2 3 4 5 6 7 before reversal 7 6 5 4 3 2 1 after reversal
We observe from this is that the first element ends up in the last position. The second element ends up in the second last position and so on. Carrying this process through we get the following exchanges.
Step1: a[1] a[7] Step2: a[2] a[6] Step3: a[3] a[5]
Step4: a[4] a[4] there is no exchange here.
Algorithm description:
reverse (a[1..n]:n integers) 1. BEGIN
2. start=0 3. end=n-1
4. Repeat while start<end temp=a[start] a[start]=a[end]; a[end]=temp; startstart+1 endend-1 5. return
Application: Used in matrix processing
Test data:
How many elements: 6 Enter 6 elements
Implementation:
/* program to array order reversal */ #include<stdio.h> #include<conio.h> main() { int a[20],n,i,temp,start,end; clrscr();
printf(“\n How many elements:”); scanf(“%d”,&n);
printf(“\n Enter %d elements”,n); for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“\n array element in order \n”); for(i=0;i<n;i++) printf(“%3d”,a[i]); start=0; end=n-1; while(start<end) { temp=a[start];
11 22 33 44 55 66 array elements in order 11 22 33 44 55 66 Reversal order 66 55 44 33 22 11 a[start]=a[end]; a[end]=temp; start++; end--; }
printf(“\n Reversal order \n”); for(i=0;i<n;i++)
printf(“%3d”,a[i]); getch();
}
Removing Duplicate Elements:
Problem: Remove all duplicates from an ordered array and contract the array accordingly. Algorithm development:
Consider the following array elements, before duplicate removal
2 2 4 6 8 8 10 12 14 16
0 1 2 3 4 5 6 7 8 9
The array elements after duplicate removal
2 4 6 8 1 0 1 2 14 16 0 1 2 3 4 5 6 7 8 9 Algorithm description: Remove_duplicate(a[1..n]:integers) BEGIN
Repeat for i=1 to n Repeat for j=i+1 to n if(a[i]==a[j]) then for(k=j;k<n;k++) a[k]=a[k+1] n=n-1 Other wise j=j+1 end for end for Return Test data: Enter size:6 Enter 6 elements Implementation:
/* a program to remove duplicate elements
in an array */
#include<stdio.h> #include<conio.h> int a[20],i,j,k,n; main() { clrscr();printf("\n Enter size:"); scanf("%d",&n);
printf("\n Enter %d elements",n); for(i=0;i<n;i++)
scanf("%d",&a[i]); printf("\n Elements \n"); for(i=0;i<n;i++)
2 2 4 5 5 7
After Duplicate Removal 2 4 5 7 printf("%d ",a[i]); for(i=0;i<n;i++) { for(j=i+1;j<n;) { if(a[i]==a[j]) { for(k=j;k<n;k++) a[k]=a[k+1]; n--; } j++; } }
printf("\n After Duplicate Removal"); for(i=0;i<n;i++)
printf("%d ",a[i]); getch();
}
Finding the K
thSmallest Element:
Problem: Given a randomly ordered array of n elements determine the Kth smallest element in the set.
Algorithm development:
Consider the following array elements, in increasing order
2 2 4 6 8 8 10 12 14 16
0 1 2 3 4 5 6 7 8 9
The first smallest element with k=1 is 2 The second smallest element with k=2 is 4
The third smallest elememnt with k=3 is 6, and so on.
We can find the Kth smallest element only we the list is in sorted manner. Algorithm description:
Ksmall(a[1..n]:integers) BEGIN
c=1
Repeat for i=1 to n if(c==k)then
print (“ Kth smallest element =”,a[i-1]) break;
if(a[i]!=a[i-1]) then c=c+1
end for Return
Implementation
#include<stdio.h> void sort(int a[],int x); main()
{
int a[20],n,k,i,c; clrscr();
printf("Enter number of elements\n"); scanf("%d",&n); printf("Enter %d elements",n); for(i=0;i<n;i++) scanf("%d",&a[i]); sort(a,n); printf("\n Enter k:"); scanf("%d",&k); if(k<=n) { c=1; for(i=1;i<n;i++) { if(c==k) {
printf("%d smallest= %d",k,a[i-1]); break; } if(a[i]!=a[i-1]) c++; } } else
printf("\n K value must be lessthan or equal to n"); getch();
}
void sort(int a[],int n) { int temp,i,j; for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if(a[i]>a[j]) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } } }
Strings:
A string is defined as an array of characters enclosed between double quotes. We can declare a string variable using following format.
char stringName[size]; where, stringName is any valid C variable name
size refers the number of characters stored in the string. Ex: char city[10];
Complier will assign a null character ‘\0’ at the end of the string. So the size should be the maximum of characters to store in the string +1.
Null character:
One of the most important issues in handling the strings is null character.
Null character is used to terminate the string. Null character is used to identify the string termination and no processing is done after the identification of null character.
The null character is not counted towards the length of the string, but takes memory of one element. Null character cannot be read or write, but is used internally only.
char college[20]=”JAGANS ENGINEERING”;
In this example the length of actual stored string is 17. In that case 18th element of the array i.e college[19] location will be used to store null character.
J A G A N S E N G I N E E R I N G \0 0 1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 Initialization of strings:
We can initialize a character array like any other arrays. Ex: char city[10]=”NELLORE”;
Ex: char city[10]={‘N’,’E’,’L’,’L‘,’O’,’R’,’E’}; N E L L O R E \
0
0 1 2 3 4 5 6 7 8 9 1
0
In both cases the null character will appended at last automatically. READING AND WRITING A STRING
A string can be read and write by using a single scanf and printf function using %S and no loop is needed.
Reading strings:
To read strings from keyboard, we use scanf( ) function with %s format specification. Ex: char city[10];
scanf(“%s”,city);
There is no need of ampersand & to read a string using scanf.
After the reading is complete, the null character is appended automatically at the next position inside the array.
The problem with scanf( ) is that it terminates its input, when the first space occurs. For example if we type ‘New Delhi’ from the keyboard, it accepts only ‘New’ to the array city.
The gets function is used to read the characters till the new line character is pressed. It also appends the null character at the end of the string automatically.
Syntax: gets(stringName); Example : char college[50]; gets(college); Writing strings :
To print a string on screen, we use the printf( ) function with %s format specification. char college[50]=”jagans college of engg and tech”;
During printing, the printf function keeps on printing the individual elements of the array till null is not reached.
The puts function is used to write strings to the screen. This function always appends the new line character after the string.
Syntax: puts(stringName);
Ex: char college[50]=”jagans college of engg and tech”; puts(college);
Processing the Strings or String Handling Functions:
C supports a number of pre-defined string handling functions of string.h, that can be used to make string manipulations.
The following are most commonly used string handling functions.
1) String copy function - strcpy( ) : This function works almost like as a string assignment operator. The general form is as follows.
strcpy(string1,string2);
It assigns the contents of string2 into string1. String2 may be a character array variable or string constant. The size of string1 should be larger enough to receive the contents of string2.
Ex: strcpy(city1,”Delhi”); strcpy(city1,city2);
2) String concatenation function – strcat( ): This function joins two strings together. It takes following general form.
Strcat( string1, string2);
This function appends the contents of string2 into string1, by removing the null character ‘\0’ at the end of the string1. The size of the string1 is large enough to accommodate the final string.
Ex: char name1[10]=”Raja”; char name2[10]=”rao” strcat(name1,name2);
3) String compare function - strcmp( ): This function compares two strings and returns a zero or
non-zero value. Its general form is as follows.
strcmp(string1,string2);
Here string1 and strings may be string variables or character constants.This function returns the ASCII numeric difference between the first non-matching characters in the strings.
Ex: x=strcmp(name1,name2); X= strcmp(“Ram”,”Rom”); 4). String Length function- strlen( ):
This function counts and returns the number of characters, without counting a null character in the string.
The general form is; n=strlen(string);
Where n is an integer variable, which receives the value of the length of the string. Ex: n=strlen(city);
n=strlen(“New York”);
strlwr(str) Converts string str to all lower case strupt(str) Converts string str to all upper case strrev(str) Reverses all characters in string str
strncpy(dest,src,n) Copies up to n character from src to dest string. strcmpi(str1,str2) Compares str1 and str2 ignoring the case sensitivity
strncat(dest,src,n) Concatenates at most n characters of src to the end of dest string. strchr(str1,ch) Scans the string str1 for the first occurrence of character ch strset(str1,ch) Sets all characters in string str1 to the character ch.
SEARCHING AND SORTING OF STRINGS
A PROGRAM TO SEARCH A SUBSTRING FROM ANY POSITION IN THE MAIN STRING #include<stdio.h> #include<conio.h> main() { char str[50],substr[10]; int len,sublen,i,j; clrscr();
printf("\n Enter a string"); gets(str);
printf("\n Enter a sub string:"); gets(substr); len=strlen(str); sublen=strlen(substr); for(i=0;i<=len-sublen;i++) { for(j=0;j<sublen;j++) { if(str[i+j]==substr[j]) continue; else break; } if(j==sublen)
printf("\n The substring is at %d onwards",i); }
getch(); }
Test data
Enter a string: jagans college of engg Enter a sub string: ege
The substring is at 11 onwards A PROGRAM TO SORT A LIST OF STRINGS #include<stdio.h>
#include<conio.h> #include<string.h> main()
{
char city[5][10],temp[10]; int i,j;
clrscr();
printf("\n Enter 5 strings \n"); for(i=0;i<5;i++)
gets(city[i]);
/*reorder the list of strings*/ for(i=0;i<4;i++) { for(j=i+1;j<5;j++) { if(strcmp(city[i],city[j]) >0) { strcpy(temp,city[i]); strcpy(city[i],city[j]); strcpy(city[j],temp); } } }
printf("\n After sorting the strings are\n"); for(i=0;i<5;i++) printf("%s\n",city[i]); getch(); } TEST DATA: