You are on page 1of 43

CSE102- DATA STRUCTURES AND ALGORITHMS

UNIT-I
Introduction
Data and Information
The collection of raw facts or descriptions about some object of interest in the mini world under
consideration is known as data.
Processed data is called as information.
Example
Consider student object of mini world university. Let us assume that we collect regno, name, sex, age,
semester-fee of each student. These are raw descriptions of a student. Hence they are called data.
If they are mentioned in the form of meaningful sentence, i.e., the register number of a student is
13BEC0001. The name of the student is XYZ. The sex of the student is Male(M) and his age is 20. He has
paid a semester fee 12500.50. Then they will be called as information.
Data type
Data type specifies the nature of the raw data.
Example
In the above example the data type of each raw data is given as below.
Raw Data
Data Type
______________________
Regno
Alpha Numeric
Name
Sting
Sex
Character
Age
Whole Number(Numeric)
Semester
Real Number or Number with fractional part (Numeric)

Data types in C
Data types in C can be broadly classified into three categories as given below.
1.Primitive / Basic /Fundamental/ Built-in Data type: It includes char, int, float, and double.
2. Derived data type: These are data types that derived from the fundamental data types. It includes
array, function and pointer.
3. User-defined data type: The data types defined by user are known as user-defined data types.
Another name to it is abstract data type. It includes structure and union.
Abstract data type (or) user-defined data type
When an application requires a special kind of data type which is not available as a built-in data type,
then it is the programmers responsibility to define that kind of data by him. Thus the programmer has
to define components of data in terms of fundamental data type along with valid operations on it.
Programmers own data type defined this way is termed abstract data type. The abstract data type is
also alternatively termed user-defined data type.
For example: Suppose user wants to process dates of the form dd-mon-yyyy. For this, no built-in data
type is available in C. Hence a programmer has to define abstract data type with name, say Date, with
M. Nagaraju, SCSE, VIT Vellore

Page 1

components defined in terms of fundamental data type along with various valid operations such as
adding/subtracting a day(s) from date to obtain another date, finding the days/months between two
dates, obtaining a day for a given date, etc., defined accordingly.
An abstract data type, in fact, can be built with the help of built-in data types and other abstract data
type(s) already built by the programmer. Some programming languages provide a facility to build
abstract data types easily. For example, using struct /class in C/ C++, programmers can define abstract
data types.
Data Structure
A data structure is a triplet denoted by (D, F, A), where
D = Data
F= Function = It is the set of valid operations on data under consideration.
A = Axioms or Rules =It is the set of rules which data and valid operations on it should follow.
Thus data structure is a collection of data along with valid operations on it and rules that the data should
satisfy
Example for data structure
In the example considered earlier, data is a student record. Valid operations are adding, deleting and
updating a record. Few fields of student record should satisfy certain rules, for example, sex column
should take either M or F only, and name field should not have any digit in it and so on.
Overview of data structures
Based on the way data got organized one can classify data structure into two main categories, namely,
linear and non-linear. Data structure is said to be linear if data in it has got organized in a sequential
manner. Linear data structure includes arrays, linked lists, stacks and queues. Data structure is said to
be non linear if data in it has got organized in a non-sequential or random manner. Non Linear data
structure includes trees, and graphs.
Linear Data Structure
All the elements in data structure are kept in
Sequential manner.

Non-linear Data Structure

All the elements in data structure are kept in
Non-Sequential manner.

Data Structures in C
i) Pointer Special type of variable that contains address of another variable
ii) Simple Variable containing single value
iii) Array Group Variable containing data items of same data type
iv) Structure Group Variable containing data items of different data type
Exercise:
1. How do you distinguish between linear and non-linear data structure?
2. How do you define terms data, information, and data type with suitable examples?
3. What is the purpose of abstract data type?
4. How many types of data types are available in C programming language?
5. Define abstract data type for student record.
6. How do you define abstract data type for date?
7. What are the data structures that available in C programming language?
M. Nagaraju, SCSE, VIT Vellore

Page 2

1. Pointer
1.1 Definition: It is a special type of variable that can hold the address of another variable. In other
words, the pointer does not hold a value in the traditional sense; instead, it holds the address of another
variable. The concept of pointer provides for accessing a variable indirect manner. They are called
pointer for the simple reason that, by storing an address, they point to a particular memory address or
location.
1.2 Uses or Advantages of pointers
The following is the list of uses of pointers
processing arrays and strings more easily and conveniently
creating complex data structures, such as linked lists and binary trees.
Fast compilation and to produce more efficient code
1.3 Operators in pointers:
There are two types of operators in pointers. They are
i)
Address of operator denoted by &
ii)
Value at address or indirection operator denoted by *. This operator is also known as
dereferencing operator.
1.4 Syntax for declaration of a pointer variable: Declaration of pointer should be distinguished from the
declaration of ordinary variables. This is accomplished by variable preceded * in the declaration
statement. Thus its syntax is as shown below.
<datatype> *variable_name;
Examples:
int *p1;
char *p2;
float *p3;

// p1 is a pointer of int data type

// p2 is a pointer of char data type
// p3 is a pointer of float data type

Note that in the above declaration statements, each pointer variable is preceded by *.
1.5 syntax for initialization of a pointer variable: It is as given below
<datatype> *variable_name = address of a variable;
Examples:
int a, *p1=&a, b, *p2=&b;
char ch, *p3=&ch;
float f, *p4=&f;
1.6 Assigning content to a pointer variable: It is as given below.
pointer_variable = address of a variable;
Example1:
int a=10, *p1;
p1=&a;
Example2:
M. Nagaraju, SCSE, VIT Vellore

Page 3

int b={10.13, 14}, *p2;

p2=&b;
Example3:
char ch=f, *p3;
p3=&ch;
Example4:
float f=1.23, *p4;
p4=&f;
1.7 Displaying content of a pointer variable: It is as shown below.
The following display the content of pointer variables given in examples of section 1.6
Example1:
*p1 10 gets displayed
Example2:
*p2 13 gets displayed
Example3:
*p3 f gets displayed
Example4:
*p4 1.23 gets displayed

1.8 Chain of pointers:

The concept of one pointer variable containing the address of another pointer variable is known chain of
pointers. This concept is also known as pointer to pointer. It is a good practice to restrict this chaining up
to a maximum of two levels.
Example:
Let a be a variable and its content be 5. Let p1 be a pointer variable containing the address of
location of variable a and p2 be another pointer variable containing the address of the pointer
variable p1.
It is diagrammatically as below
Name
p2 (pointer)
p1 (pointer)
a (ordinary variable)
2002

1)
p1

1010

3012
2002
== > &a == > contains address of ordinary variable a

1010

2)

p2

== > &p1

3)

**p2

== >

4)

*p1

*(*&p1) == >

*p1

== > *(&a) == > a == > content of a gets displayed.

Page 4

1.9 Rules (or) Valid Pointer Arithmetic (or) Valid Pointer Expressions:
Let us consider the expressions involving pointers first. Then determine whether these expressions are
valid or invalid. We will also provide the reason for invalid expressions.
i) Assigning an absolute value to a pointer is invalid. It is illustrated in the following example.
Example: Let a be integer variable with memory address 2010. Let p1 is a pointer of integer type and
pointing to variable a. Then the assignment statement, such as, p1=2010 is invalid. It has to be done as
p1=&a;
ii)Let p1 and p2 be two pointers of same data type. Then the assignment statement either p1=p2 or
p2=p1 will be valid. Assignment statement involving two pointers of different data types is invalid.
iii)Let p1 be a pointer and n be an integer. Then adding or subtracting n from p1, i.e., p1+n or p1-n, is
valid only when p1 is a pointer to an array and the result of the statement lies within the boundary of
address of an array. Otherwise it is invalid statement.
Example1:
char str=VIT UNIVERSITY, *p1;
int n=3;
p1=&str;
p1+n; // valid as it gives address of 4th element of an array
Example2:
char str=VIT UNIVERSITY, *p1;
int n=3;
p1=&str;
p1=p1-n; // invalid as it results in underflow of an array
Example3:
char str=VIT UNIVERSITY, *p1;
int n=3;
p1=&str;
p1=p1+n; // invalid as it results in overflow of an array
Note: If pointer p1 points to simple integer variable, then adding/subtracting some integer n from it
results in some address. Thus it is a valid expression.
iv)Incrementing / decrementing pointer variable, i.e., p1++ or p1--, results in some address which is
valid. The increment or decrement happens in terms of scale factor of the data type of pointer.
v) Adding , multiplying and dividing two pointers of same data type, i.e., p1+p2, p1*p2, and p1/p2, are
always invalid.
vi) Subtracting two pointers of same data type, i.e., p1-p2, is valid only when the pointers points to the
same array and result of this expression lies within the boundary of address of an array. Otherwise it is
invalid.
Example:
int a={10,21,32,11,16}, *p1,*p2;
M. Nagaraju, SCSE, VIT Vellore

Page 5

p1=&a; // points to first element of an array

p2=&a; // points to last element of an array
p2-p1; // valid as its result specifies size of an array when it is divided by the scale of the data type of the
pointers.
p1-p2; // Invalid as its result falls out of range of addresses of the array.
vii) Multiplying and Dividing a pointer by an integer, i.e., p1*n, and p1/n, are always invalid.
viii) Comparing two pointers, i.e., p1<p2, p1<=p2, p1>=p2,p1>p2, p1!=p2 and so on, is valid only when
pointers points to an array and the result lies within the boundary of address of an array. Otherwise it is
invalid.
Example 1:
char str=VIT UNIVERSITY, *p1, *p2;
p1=&str;
p2&str;
p1>p2; // valid as results in true
p2>p1; // valid as results in false
ix) Any expression involving value at address of pointer variables is valid. The list of these expressions is
as shown below.
i)
*p1=*p2 is valid.
ii)
*p1 + *p2 is valid
iii)
*p1 - *p2 is valid
iv)
*p1**p2 is invalid as ** is considered as exponential symbol. The right way to write
this expression is as below
*p1 * *p2 is valid
v)

vi)
vii)
viii)

*p1/*p2 is invalid as /* can be treated of starting of comment. The right way to write
this expression is as below
*p1 / *p2 is valid
*p1+n, *p1-n, *p1*n, *p1/n expressions are all valid
*p1 =*p2, *p1 != *p2, *p1<*p2, and so on are all valid
*p1++, *p1- - etc., expressions are all valid.

Exercise:
1. The two operators in pointers are ____________ and ____________.
2. Pointer can be distinguished from ordinary variable in declaration section by ___symbol.
3. Assigning pointer of one type to another type is possible. State whether the statement is true or false.
4. Let arr be a pointer variable. Then (arr+n) is same as arr[n]. State whether the statement is true or
false. If false give the reason.
5. One cannot think of increment and decrement operators with pointers like them with ordinary
variable. Why is it so? Specify the reason.
6. State whether dividing a pointer variable by an integer is valid or not
7. State whether adding of two pointers of the same type is valid or not.
8. Pick the right alternative from the following that means same as value at address
B) dereferencing operator
C) content operator
D) none of these
9. Let p1 and p2 be two pointers of same data type. Then state the condition for pointer comparison and
M. Nagaraju, SCSE, VIT Vellore

Page 6

subtraction to be valid.
10. Pointer allows the user to access the variable _____________ manner.
1.9 Call by reference (or) address
The following program shows the logic for swapping of values of two variables using call by address.
#include<stdio.h>
#include<conio.h>
void swap(int *x, int *y); // function declaration / prototype
int main()
{
int a=10,b=20;
printf(The values of a and b before swapping\n, a, b);
swap(&a,&b); // function call
printf(The values of a and b after swapping\n, a,b);
getch(); return 0;
}
//function definition
void swap (int *x, int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
1.10 Pointer and 1D Array
For explanation of this topic refer class notes.
The following programs illustrate the usage of pointer to one-dimensional array.
Program 1: The C program to reverse 1D array elements using pointer to it.
#include<stdio.h>
#include<conio.h>
void main()
{
int a, i, n,*p, temp;
p=&a;
printf("Enter number of elements of an array\n");
scanf("%d",&n);
printf("Enter elements of an array\n");
for(i=0;i<n;i++)
scanf("%d",p+i);
printf("Array elements are\n");
for(i=0;i<n;i++)
printf("%d\n",*(p+i));
printf("The reverse array is\n");
for(i=0;i<=n/2;i++)
M. Nagaraju, SCSE, VIT Vellore

Page 7

{
temp= *(p+i);
*(p+i)=*(p+n-1-i);
*(p+n-1-i)=temp;
}
for(i=0;i<n;i++)
printf("%d\n",*(p+i));
getch();
}
Program 2: The C program to display array elements using pointer to it.
#include<stdio.h>
#include<conio.h>
int main()
{
int a, i, n,*p, temp;
p=&a;
printf("Enter number of elements of an array\n");
scanf("%d",&n);
printf("Enter elements of an array\n");
for(i=0;i<n;i++)
scanf("%d",p+i);
printf("Array elements are\n");
for(i=0;i<n;i++)
printf("%d\n",*(p+i));
getch();
return 0;
}
Program 3: The C program to display array elements in reverse using pointer to it.
#include<stdio.h>
#include<conio.h>
int main()
{
int a, i, n,*p, temp;
p=&a;
printf("Enter number of elements of an array\n");
scanf("%d",&n);
printf("Enter elements of an array\n");
for(i=0;i<n;i++)
scanf("%d",p+i);
printf("Array elements are\n");
for(i=n-1;i>=0;i--)
printf("%d\n",*(p+i));
getch();
return 0;
}

M. Nagaraju, SCSE, VIT Vellore

Page 8

Program 4: The C program to find the smalles element of 1D array using pointer to it.
#include<stdio.h>
#include<conio.h>
int main()
{
int a,i,n,*p,small;
p=&a;
printf("Enter number of elements in an array\n");
scanf("%d",&n);
printf("Enter %d elements into an array\n",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
printf("Array elements\n") ;
for(i=0;i<n;i++)
printf("%d\n",*(p+i));
small=*(p+0);
for(i=1;i<n;i++)
if(small > *(p+i))
small=*(p+i);
printf("The smallest element in an array is %d\n",small);
getch(); return 0;
}
Program 5: The C program to search for a particular in 1D array using pointer to it.
#include<stdio.h>
#include<conio.h>
int main()
{
int a,i,n,*p, element, pos=0;
p=&a;
printf("Enter number of elements in an array\n");
scanf("%d",&n);
printf("Enter %d elements into an array\n",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
printf("Array elements\n") ;
for(i=0;i<n;i++)
printf("%d\n",*(p+i));
printf(Enter element to be searched in an array\n);
scanf(%d,&element);
for(i=1;i<n;i++)
if(*(p+i)== element){
pos=i+1;
break;
}
If(pos==0)
M. Nagaraju, SCSE, VIT Vellore

Page 9

else
printf("The element %d is found at position %d\n",element, pos);
getch();
return 0;
}
Program 6: The C program to sort elements of 1D array in ascending order using pointer to it.
#include<stdio.h>
#include<conio.h>
int main()
{
int a,i,j,n,*p;
p=&a;
printf("Enter number of elements in an array\n");
scanf("%d",&n);
printf("Enter %d elements into an array\n",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
printf("Array elements before sorting\n") ;
for(i=0;i<n;i++)
printf("%d\n",*(p+i));

/* Sorting */
for(i=0;i<n-1;i++)
for(j=1;j<n;j++)
if(*(p+i)>*(p+j){
temp=*(p+i);
*(p+i)=*(p+j);
*(p+j)=temp;}
printf("Array elements after sorting\n") ;
for(i=0;i<n;i++)
printf("%d\n",*(p+i));
getch(); return 0;
}
Exercise:
1) Write a C program to find the sum of even numbers in 1D array using pointer to it.
Soln.
#include<stdio.h>
#include<conio.h>
int main()
{
int a,i,n,*p,sum=0;
p=&a;
printf("Enter number of elements in an array\n");
M. Nagaraju, SCSE, VIT Vellore

Page 10

scanf("%d",&n);
printf("Enter %d elements into an array\n",n);
for(i=0;i<n;i++)
scanf("%d",p+i);
printf("Array elements\n") ;
for(i=0;i<n;i++)
printf("%d\n",*(p+i));
for(i=0;i<n;i++)
if(*(p+i)%2==0)
sum=sum+ *(p+i);
printf("The sum of even values in an array is %d\n",sum);
getch(); return 0;}
2) Write a C program to find the sum of numbers divisible by 3 in 1D array using pointer to it.
3) Write a C program to arrange elements of an array in descending order using pointer to it.
4) Write a C program to count number of even and odd numbers in an array using pointer to it.
1.11 Pointer and 2D Array:
For explanation of this topic refer class notes.
Let given matrix be a and pointer to it be p1. Then the following formula helps us to manipulate
matrix using pointer to it.
Base address + (row index * number of columns) + column index
Suppose p1=&a and I and j denote row and column indexes, and r and c denote number of rows
and columns of a matrix, then the above formula can be represented as
p1+ i * c + j
(p1+i*c+j)
it denotes the address of (I,j)th element of the matrix
*(p1+i*c+j)
It denotes the (I,j)th element of the matrix
The following programs illustrate the usage of pointer to two-dimensional array.
Program 1: The C program to display matrix using pointer to it.
#include<stdio.h>
#include<conio.h>
int main()
{
int a,i,j,r,c,*p;
p=&a;
printf("Enter number of rows of a matrix\n");
scanf("%d",&r);
printf("Enter number of columns of a matrix\n");
scanf("%d",&c);
printf("Enter a matrix\n");
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf("%d",(p+i*c+j));
printf("The matrix is\n");
M. Nagaraju, SCSE, VIT Vellore

Page 11

for(i=0;i<r;i++) {
for(j=0;j<c;j++)
printf("%d ",*(p+i*c+j));
printf("\n");
}
getch(); return 0;
}
Program2: The C program to find the transpose of a matrix using pointer to it.
#include<stdio.h>
#include<conio.h>
int main()
{
int a,r,c,*p1,*p2,i,j;
printf("Enter number of rows and colums of the matrix\n");
scanf("%d%d",&r,&c);
p1=&a;
printf("Enter element of matrix\n");
for(i=0;i<r;i++)
for(j=0;j<c;j++){
scanf("%d",(p1+i*c+j));
}
printf("The matrix is \n");
for(i=0;i<r;i++){
for(j=0;j<c;j++)
printf("%d ",*(p1+i*c+j));
printf("\n");
}
printf("The transpose matrix is\n");
for(i=0;i<r;i++)
for(j=0;j<c;j++)
*(p2+j*r+i)=*(p1+i*c+j);
for(i=0;i<c;i++){
for(j=0;j<r;j++)
printf("%d ",*(p2+i*r+j));
printf("\n");
}
getch();
return 0;
}
Exercise:
1) Write a C program to find the sum of elements of both diagonals of a matrix using pointer to it.
Soln.
#include<stdio.h>
#include<conio.h>
int main()
{
int a,i,j,r,c,sum1=0,sum2=0,*p;
M. Nagaraju, SCSE, VIT Vellore

Page 12

p=&a;
printf("Enter number of rows of a matrix\n");
scanf("%d",&r);
printf("Enter number of columns of a matrix\n");
scanf("%d",&c);
if(r==c)
{
printf("Enter a matrix\n");
for(i=0;i<r;i++)
for(j=0;j<c;j++){
scanf("%d",(p+i*c+j));
if(i==j)
sum1=sum1+*(p+i*c+j);
if(i+j==r-1)
sum2=sum2+*(p+i*c+j);
}
printf("The matrix is\n");
for(i=0;i<r;i++) {
for(j=0;j<c;j++)
printf("%d ",*(p+i*c+j));
printf("\n");
}
printf("The sum of principle diagonal elements is %d\n",sum1);
printf("The sum of other diagonal elements is %d\n",sum2);
}
else
printf("Enter square matrix only\n");
getch(); return 0;
}
2) Write a C program to count number of even elements in 2D array using pointer to it.
1.12 Pointer and 1D string:
For the explanation of this topic refer class notes.
The following programs illustrate usage of pointer to 1D string.
Program 1: The C program to display string character by character using pointer to it.
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char str="VIT UNIVERSITY",*p1;
p1=&str;
while(*p1){
putchar(*p1++);
getch();}
getch();return 0;}
M. Nagaraju, SCSE, VIT Vellore

Page 13

Program 2: The C program to display string in reverse character by character using pointer to it.
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char str="VIT UNIVERSITY",*p1,i;
p1=&str; i=0;
while(i<15){
putchar(*p1--);
getch();i++;}
getch();return 0;}
Program 3: The C program to find the reverse of a string using pointer to it.
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char str1="VIT UNIVERSITY", *begin,*end,temp;
int i,len=0;
printf("Enter a string\n");
gets(str1);
len=strlen(str1);
begin=&str1;
end=&str1;
for(i=0;i<len-1;i++)
end++;
for(i=0;i<=len/2;i++)
{
temp=*end;
*end=*begin;
*begin=temp;
begin++;
end--;
}
puts("The reverse string is");
puts(str1);
getch(); return 0;}
Program 4: The C program to find string length using pointer to it.
#include<stdio.h>
#include<conio.h>
int main()
{
char str="VIT UNIVERSITY",*p1, len=0;
for(p1=&str;*p1!=\0;*p1++){
M. Nagaraju, SCSE, VIT Vellore

Page 14

len++;}
printf("The length of the given string is %d\n", len);
getch(); return 0;}
Program 5: The C program for string copy using pointer to a string.
#include<stdio.h>
#include<conio.h>
int main()
{
char str1,str2,*p;
int i=0;
printf("Enter the string\n");
gets(str1);
for(p=&str1;*p!='\0';p++){
str2[i++]=*p;
}
str2[i]='\0';
printf("copied string is %s\n",str2);
getch(); return 0;}
Exercise:
1.Write a C program to implement string concatenation function using pointer it
Soln.
#include<stdio.h>
#include<conio.h>
int main()
{
char str1,str2,*p;
int len=0,i=0;
printf("Enter first string\n");
gets(str1);
printf("Enter second string\n");
gets(str2);
for(len=0;str1[len]!='\0';len++);
for(p=&str2;*p!='\0';p++){
str1[len++]=*p;
}
str1[len]='\0';
printf("Cancated string is %s\n",str1);
getch(); return 0;}
Program 7: The C program to check whether the read string is palindrome or not using pointer to it.
#include<stdio.h>
#include<conio.h>
#include<string.h>
M. Nagaraju, SCSE, VIT Vellore

Page 15

int main()
{
char str1,*p,rstr;
printf("Enter the string\n");
gets(str1);
p=&str1;
strcpy(rstr,p);
strrev(rstr);
if(strcmp(rstr,p)==0)
printf("%s is a palindrome\n",p);
else
printf("%s is not a palindrome\n",p);
getch(); return 0;}
Try the following program by yourself
1.Write a C program to implement string compare function using pointer to it
Exercise:
1.Consider the following code snippet and find out its output
int a={10,9,11,8,12};
int i;
for(i=4;i>=0;i--)
printf("%d ",*(a+i));
Ans)

Output: 12 8 11 9 10

2.Let us consider the following declaration

char s1[]=India is beautiful country
char s2[]=C is sea
char s3[];
Let us now find out the value of the each of the following expression
Expression
Value
strlen(s1)
28
strlen(s2+5)
3
printf(%s, s1+10)
beautiful country
strcpy(s3,s2+5)
S3 will contain sea
printf(%s,s3)
sea
3. Let us consider the following
char str1[]=India is beautiful country; char str2[];
What is the value of the following statements?
i)strlen(str1+8)
ii) strcpy(str3,str1+10)
iii)strrev(str3)

iv)strlen(str3)

Page 16

1.13 Pointer and 2D string :

Program 1:Write a C program to display list of names using pointer to it.
#include<conio.h>
#include<string.h>
int main()
{
char str,*p1;
int i,n;
printf("Enter number of names in the list\n");
scanf("%d",&n);
for(i=0;i<n;i++)
p1[i]=str[i];
printf("Enter list of names\n");
for(i=0;i<n;i++)
scanf("%s",p1[i]);
printf("The name list is\n");
for(i=0;i<n;i++)
puts(*(p1+i));
getch();
}
Program 2:Write a C program to search for a particular name in the list of names using pointer to it.
#include<conio.h>
#include<string.h>
int main()
{
char str,*p1,name;
int i,n,pos=0;
printf("Enter number of names in the list\n");
scanf("%d",&n);
for(i=0;i<n;i++)
p1[i]=str[i];
printf("Enter list of names\n");
for(i=0;i<n;i++)
scanf("%s",p1[i]);
printf("Enter name to be searched in the list\n");
scanf("%s",name);
for(i=0;i<n;i++)
if(strcmp(*(p1+i),name)==0){
pos=i+1;
break;
}
if(pos!=0)
printf("%s found in the list at the position %d\n",name,pos);
else
getch(); return 0;}
M. Nagaraju, SCSE, VIT Vellore

Page 17

Program 2:Write a C program to sort list of names in ascending order using pointer to it.
#include<conio.h>
#include<string.h>
int main()
{
char str,*p1,temp;
int i,j,n;
printf("Enter number of names in the list\n");
scanf("%d",&n);
for(i=0;i<n;i++)
p1[i]=str[i];
printf("Enter list of names\n");
for(i=0;i<n;i++)
scanf("%s",p1[i]);
printf("List of names before soring\n");
for(i=0;i<n;i++)
puts(*(p1+i));
for(i=0;i<n-1;i++)
for(j=1;j<n;j++)
if(strcmp(*(p1+i),*(p1+j))>0){
strcpy(temp,*(p1+i));
strcpy(*(p1+i),*(p1+j));
strcpy(*(p1+j),temp);
}
printf("List of names after sorting\n");
for(i=0;i<n;i++)
puts(*(p1+i));
getch(); return 0; }
1.13.1 Array of pointers vs 2D string:
Array of pointers is a collection of pointers of same type under one name. Array of pointers is usually
used for pointing list of strings and records of variable sizes. This concept leads to ragged arrays which in
turn saves memory. This concept is illustrated as below.
Ragged array with saving memory space:
Let array of pointers pointing to 5 strings be declared as
char *univptr;
This declaration statement creates an array of 5 character pointers, each of which can be used to point
to a string. Thus first pointer denoted by univptr, second pointer denoted by univptr, and so on up
to last pointer denoted by univptr. As they are uninitialized, they point to some unknown point in
memory. By initializing them one could make them point to strings in memory. It can be done as shown
below.
int *univptr={"VIT","BITS","IIT","ANNA","OSMANIA"};

Page 18

Diagrammatic representation of the above line of code is as shown below

Array of Pointers
Strings Stored
Memory allocated to each string

4 bytes
5 bytes
4 bytes
5 bytes
8 bytes
-------------------Total memory space allocated is
26 bytes
-------------------This way array of pointers results in ragged arrays. Ragged array is a concept by which a set of
strings/records can be stored as per their variable sizes. It is advantageous over array of strings as it
saves memory, because it will not allocate fixed length memory to each string/record in the collection
rather will allocate variable length memory as per the string/record size to be stored.
univptr
univptr
univptr
univptr
univprt

VIT \0
BITS \0
IIT\0
ANNA\0
OSMANIA\0

Let us now see the implementation of the above example using 2D array of strings which is shown as
below.
Let array of 5 strings be declared and initialized as below
char univ = {"VIT","BITS","IIT","ANNA","OSMANIA"};
Diagrammatic representation of the above line of code is as shown below
2D Array
Strings Stored
Memory allocated to each string

univ
univ
univ
univ
univ

VIT \0bbbb
BITS\0bbb
IIT\0bbbb
ANNA\0bb
OSMANIA\0

8 bytes
8 bytes
8 bytes
8bytes
8 bytes
--------------------

Where b stands for blank space

Total memory space allocated is
40 bytes
-------------------One can clearly observe from the above example that array of pointers in deed results in saving of
memory.
Program 1:
#include<stdio.h>
void main(){
char *name={"VIT","BITS","IIT","Anna","Osmania"};
int i;
printf("Display list of university names\n");
for(i=0;i<5;i++)
printf("%s\n",name[i]);
system("pause");
}
M. Nagaraju, SCSE, VIT Vellore

Page 19

1.14 Pointers and Simple Structures:

For explanation of this topic refer class notes.
The usage of pointer to simple structure is illustrated by the following example.
#include<stdio.h>
#include<conio.h>
struct product{
char pname;
int price;
int quantity;
}prod;
void total_cost(struct product *p);
int main()
{ struct product *p;
p=&prod;
printf("Enter product name\n");
scanf("%s",p->pname);
printf("Enter price of a product\n");
scanf("%d",&p->price);
printf("Enter quantity of a product\n");
scanf("%d",&p->quantity);
total_cost(p);
getch(); return 0;
}
void total_cost(struct product *ptr){
printf("Product name=%s\n",ptr->pname);
printf("Product price=%d\n",ptr->price);
printf("Product quantity=%d\n",ptr->quantity);
printf("product total_cost=%d\n",ptr->price*ptr->quantity);
}
NOTE :
pointer-to-structure -> membername is equivalent to
(*pointer-to-structure). membername
Exercise: Try the following programs by yourself.
1. Write a program to display total amount to be paid by the customer as electricity charge by passing
pointer to a structure electricity with fields, namely, meterno, cname, units as parameter to function
total_chagre()
2. Write a program to display display grade of a student by passing pointer to a structure student with
fields, namely, regno, name, m1, m2, m3, m4, m5 as parameter to function grade()

Page 20

1.15 Pointer and Array of Structure:

For explanation of this topic refer class notes.
The usage of pointer to an array of structure is illustrated by the following example
#include<stdio.h>
struct product{
char pname;
int price;
int quantity;
}prod;
void total_cost(struct product *p);
int main(){
struct product *p;
int n;
printf("Enter number of products\n");
scanf("%d",&n);
for(p=&prod;p<prod+n;p++) {
printf("Enter product name\n");
scanf("%s",p->pname);
printf("Enter price of a product\n");
scanf("%d",&p->price);
printf("Enter quantity of a product\n");
scanf("%d",&p->quantity);
total_cost(p);
}
getch(); return 0;}
void total_cost(struct product *ptr){
printf("Product name=%s\n",ptr->pname);
printf("Product price=%d\n",ptr->price);
printf("Product quantity=%d\n",ptr->quantity);
printf("product total-cost=%d\n",ptr->price*ptr->quantity); }
Exercise : Try the following programs by yourself
1. Write a program to display total amount to be paid by the customer as electricity charge by passing
pointer to an array of structure electricity with fields, namely, meterno, cname, units as parameter to
function total_chagre()
2. Write a program to display display grade of a student by passing pointer to an array of structure
student with fields, namely, regno, name, m1, m2, m3, m4, m5 as parameter to function grade()
1.15.1 Fast and efficient way of sorting of strings/records with out disturbing them in data array:
Let us store the given strings/records in data array and have array of pointers pointing to them.
Point 1: One can sort strings either in ascending or descending order without actually disturbing them in
data array rather by just reorganizing the pointers to them in array of pointers accordingly.
The following example illustrates the above point

M. Nagaraju, SCSE, VIT Vellore

Page 21

Example 1:
Array of pointers

Data Array

strptr
strptr
strptr
strptr
strptr

V IT\0
BITS\0
ANNA\0
ANDHRA\0
VENKATESWARA\0

Explanation:
The following statement displays universities names in ascending order without disturbing their
positions in data array
for(i=0;i<5;i++)
printf(%s\t,*strptr[i]);
Output: ANDHRA

ANNA

BITS

VENKATESWARA

VIT

Point 2: One can sort records based on different fields without actually disturbing them in data array
rather by just reorganizing the pointers to them in array of pointers accordingly.
The following examples illustrate the above point.
Example 2: Sorting records in ascending based on regno field of a record.
Array of pointers
Data Array_____
Regno Mob
Total
____________________
recptr
102
Jan
589
recptr
100
Feb
565
recptr
101
Mar
590
recptr
104
Apr
566
recptr
103
May
551
Explanation:
The following statement displays record in ascending order based on Regno field without disturbing
their positions in data array
for(i=0;i<5;i++)
printf(%s\n,*recptr[i]);
Output:
100
Feb
101
Mar
102
Jan
103
May
104
Apr

565
590
589
551
566

Page 22

Example 3: Sorting records in ascending based on Month of birth(Mob) field of a record.

Array of pointers
Data Array_____
Regno Mob
Total
____________________
recptr
102
Jan
589
recptr
100
Feb
565
recptr
101
Mar
590
recptr
104
Apr
566
recptr
103
May
551
Explanation:
The following statement displays record in ascending order based on Mob field without disturbing their
positions in data array
for(i=0;i<5;i++)
printf(%s\n,*recptr[i]);
Output:
104
Apr
566
100
Feb
565
102
Jan
589
101
Mar
590
103
May
551
Exercise:
1 .Difference between an array of pointers and pointer to an array is as shown below
Ans)
Array of pointer
Pointer to an array
Declaration
Declaration
data_type *array_name[size];
data_type (*array_name)[size];
size represents the number of rows.
size represents the number of columns.
The space for columns may be
The space for the rows may be
dynamically allotted.
dynamically allotted.
2. What are the advantages of array of pointers?
3. What is a ragged array? How is it better than ordinary 2D array of strings? Illustrate it with suitable
example.
1) Compilation of pointer implementation of data structures is very fast.
2) Pointers facilitate Call by Reference (or) Address concept.
3) Array of pointers is better than 2D strings as it leads to ragged arrays which saves lot of
memory.
4) Array of pointers makes operations on strings/records very efficient and fast.
queue, linked priority queue, trees, and graphs and implementation of their operations very
simple and flexible.
6) Pointers support dynamic memory allocation which avoids memory wastage.

2.Simple Variable
M. Nagaraju, SCSE, VIT Vellore

Page 23

2.1 Definition: An identifier that stores single value. The value may change during the program
2.2 Declaration: Declaration syntax is as shown below
datatype variablename1, variablename2;
2.3 Initialization: The syntax is as shown below
datatype variablename1=value1, variabalename2=value2;
2.4 Assigning value to a variable: The syntax is as shown below
Variablename1=value1;
2.5 Passing simple variable as argument to function: It is possible in the following two ways.
a) call-by-value
b) call-by-reference
2.6 The following example illustrates call-by-value and call-by-reference concept:
#include<stdio.h>
int main(){
int a, b=2;
void modify(int , int);

// Function declaration

printf(Enter the value of a\n);

scanf(%d,&a);
printf( The value of a=%d and b=%d before function call\n, a , b);
modify(a,b); // Function call by call-by-value method;
// A copy of variables a and b are passed
// to its function definition; and Arguments in
// the function call are called
// Actual arguments
printf( The value of a=%d and b=%d after function call\n, a, b);
getch(); return 0; }
void modify( int a, int b) // Function definition; and Arguments in it are called
// Formal arguments
{
a=a+2; b=b-1;
printf(The value of a=%d and b=%d with in function definition, a, b); }
Input/Output:
Enter the value of a
7
The value of a=7 and b=2 before function call
The value of a=9 and b=1 with in function definition
The value of a=7 and b=2 after function call
2.7 The following example illustrates call-by-value and call-by-reference concept:
M. Nagaraju, SCSE, VIT Vellore

Page 24

#include<stdio.h>
int main(){
int a, b=2;
void modify(int * , int *);

//Function declaration and * in the declaration

//specifies that the variable is pointer type

printf(Enter the value of a\n);

scanf(%d,&a);
printf( The value of a=%d and b=%d before function call\n, a , b);
modify(&a,&b); //Function call by call-by-reference; Addresses of variables
//a and b are passed to its function de finition;and
// arguments in the function call are called
// Actual arguments
printf( The value of a=%d and b=%d after function call\n, a, b);
getch(); return 0;
}
void modify( int *a, int *b) //Function definition and symbol *
// specifies the variables as pointer type; and
//arguments in it are called Formal arguments
{
*a = *a + 2;
// Symbol * in these two statements
*b = *b - 1;
printf(The value of a=%d and b=%d with in function definition, a, b);
}
Input/Output:
Enter the value of a
7
The value of a=7 and b=2 before function call
The value of a=9 and b=1 with in function definition
The value of a=9 and b=1 after function call
Exercise:
1. In call-by-address _location_ of the variable(s) passed as parameter to function call.
2. In call-by-value __copy of value__ of the variable(s) passed as parameter to function call.
3. The parameters or arguments in function call are known as ____actual___
4. The parameters or arguments in the header of function definition are known as ___formal__.
5. State three rules required to map formal and actual arguments correctly.
Ans) Number, data type and order of arguments should match
6. The value of a variable can be accessed indirectly using _indirection or value at address___ operator.

M. Nagaraju, SCSE, VIT Vellore

Page 25

3. Array
3.1 Definition: It is a collection of finite number of homogeneous data elements stored in linear order.
The following are the terminology associated with array concept.
Size: It specifies the number of elements in an array. It is also called length or dimension of an
array.
Type: It specifies the kind of data type it is meant for. For example, an array of integers, an array
of character strings, etc.
Base: It specifies the address of the memory location of the first element of an array.
Index: All the elements in an array can be referenced by a subscript like A[I]. This subscript is
known as index. An index is always an integer value. As each array element is identified by a
subscript or index, an array element is also termed subscripted or indexed variable.
Range of indices: Indices of array elements may change from a lower bound (L) to an upper
bound (U), and these bounds are called the boundaries of an array.

i)
ii)

One Dimensional Array (1D Array)

Multi Dimensional Array (2D Array or Matrix, 3D Array and so on)

For each array type students have to recollect the topics, such as, i) Declaring
ii) Initializing
iii) Assigning values iv) Displaying elements of an array etc., and also recollect the problems done on
them in the course CSE101 of semester I.
3.2 One Dimensional Array (1D Array)
3.2.1 Various operations that can be performed on an array are: traversing, sorting, searching,
insertion, deletion, and merging.
Algorithm TraverseArray
Input: An array A with elements.
Output: According to Visit().
Data Structure: Array A[L U].
Steps
1.i=L
2. While i<=U do
3.
visit(A[i])
4.
i=i+1
5.EndWhile
6.Stop
Algorithm SortArray
Input: An array with integer data.
Output: An array with sorted elements in an order according to Order().
Data structures: An integer array A[L . U].
Steps
1. i=U
M. Nagaraju, SCSE, VIT Vellore

Page 26

2. While i>=L do
3.
j=L
4.
While j<I do
5.
If Order(A[j],A[j+1]) = FALSE
6.
Swap(A[j],A[j+1])
7.
EndIf
8.
j=j+1
9.
EndWhile
10.
i=i-1
11. EndWhile
12. Stop
Algorithm SearchArray
Input: KEY is the element to be searched.
Output: Index of KEY in A or a message on failure.
Data structures: An array A[L . U].
Steps
1. i=L, found=0, location=0
2. While(i<=U) and (found=0)do
3.
If Compare(A[i],KEY)=TRUE then
4.
found=1
5.
location=i
6.
Else
7.
i=i+1
8.
EndIf
9. EndWhile
10. If found=0 then
11.
Print Search is unsuccessful: KEY is not in the array
12. Else
13.
Print Search is successful: KEY is in the array at location, location
14. EndIf
15. Return(location)
16. Stop.
Algorithm InsertArray
Input: KEY is the item, LOCATION is the index of the element where it is to be inserted.
Output: Array enriched with KEY.
Data structures: An array A[L . U].
Steps
1.If A[U]!=NULL then
2.
Print Array is full: No insertion possible
3.
Exit
4.Else
5.
i=U
6.
While i>LOCATION do
7.
A[i]=a[i-1]
8.
i=i-1
9.
EndWhile
M. Nagaraju, SCSE, VIT Vellore

Page 27

10.
A[LOCATION]=KEY
11.EndIf
12.Stop
Algorithm DeleteArray
Input: KEY the element to be deleted.
Output: Slimed array without KEY.
Data structures: An array A[L . U].
Steps
1.i=SearhArray(A, Key)
2. If(i=0) then
3.
4.
Exit
5.Else
6.
While i<U do
7.
A[I]=A[I+1]
8.
i=i+1
9.
EndWhile
10.Endif
11.A[U]=NULL
12.U=U-1
13.Stop
Algorithm Merge
Input: Two array A1[L1 . U1], A2[L2 . U2]
Output: Resultant array A[L . U], where L=L1 and U=U1+(U2-L2+1) when A2 is appended after A1.
Data structure: Array structure
Steps
1.I1=L1, i2=L2;
2.L=L1, U=U1+U2-L2+1
3. I=L
4.AllocateMemory(Size(U-L+1))
5. While i1<=U1 do
6.
A[i] =A1[i]
7.
i=i+1, i1=i1+1
8.EndWhile
9.While i2<U2 do
10.
A[i]=A2[i2]
11.
i=i+1, i2=i2+1
12.EndWhile
13. Stop
3.2.2 Passing 1D array as parameter to a function
Let us discuss it with the following example.
Making a program to find the biggest element of 1D array using function biggest()
#include<stdio.h>
void biggest(int a, int );

M. Nagaraju, SCSE, VIT Vellore

Page 28

void main()
{
int a,i,n;
printf(Enter size of an array\n);
scanf(%d,&n);
printf(Enter the elements of an array\n);
for(i=0;i<n;i++)
scanf(%d,a[i]);
biggest(a,n);
system(pause);
}
void biggest(int x, int m)
{
int i,big=0;
for(i=0;i<m;i++)
if(big<a[i])
big=a[i];
printf(The biggest element of an array is %d\n,big);
}

3.3 Multi Dimensional Array

Matrix or Two Dimensional Array (2D Array) and Three Dimensional Array(3D Array) are two examples of
multidimensional arrays. The following sections describe the multidimensional arrays.
3.3.1 Two Dimensional Arrays (2D Arrays)
It is a collection of homogeneous elements where the elements are ordered in a number of rows and
columns. An example of m x n matrix where m denotes the number of rows and n denotes the number of
columns, is as follows:

a00
a10
.
.
am-10

a01
a11
.
.
am-11

.. a0n-1
.. a1n-1
.
.

am-1n-1

The subscripts of any element of the above matrix represent the row and the column of that element.
3.3.2 Memory representation of a matrix
Like one-dimensional arrays, matrices are also stored in contagious memory locations. There are two
conventions of storing any matrix in the memory:
1.Row-major order
2.Column-major order
In row-major order, the elements of a matrix are stored on a row-by-row basis, that is, all the elements in the
M. Nagaraju, SCSE, VIT Vellore

Page 29

first row, then in the second row, and so on. On the other hand, in column-major order, elements are stored
column by column, that is all the elements in the first column are stored in their order of rows, then in the
second column, and so on. For example, consider a matrix A of order 3 x 4:

a00
a10
a20

a01
a11
a21

a02
a12
a22

a03
a13
a23

This matrix can be represented in the memory as shown below

Row-major order
a00
a01
a02
a03
a10
a11
a12
a13
a20
a21
a22
a23

Column-major order
a00
a10
a20
a01
a11
a21
a02
a12
a22
a03
a13
a23

3.3.3 Passing 2D array as parameter to a function

Let us discuss it with the following example.
Making a program to display the elements of an 2D array using function display
#include<stdio.h>
#include<conio.h>
void display(int a, int, int);
void main(){
int a,i,j,r,c;
printf("Enter size of a matrix\n");
scanf("%d%d",&r,&c);
printf("Enter elements of an array\n");
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf("%d",&a[i][j]);
display(a,r,c);
getch();
}
M. Nagaraju, SCSE, VIT Vellore

Page 30

void display(int x, int m, int n)

{
int i,j;
printf("The matrix is\n");
for(i=0;i<m;i++){
{
for(j=0;j<n;j++)
printf("%d ",x[i][j]);
printf("\n");}
}
}
3.4 Sparse matrices
A sparse matrix is a two-dimensional array where the majority of the elements have the value null. In a large
number of applications, sparse matrices are involved. As far as the storage of a sparse matrix is concerned,
storing of null elements cause wastage of memory. So, we should devise a technique such that only non-null
elements will be stored. One approach is to use the linked list. Some well-known sparse matrices which are
symmetric in form can be classified as follows:
Sparse matrices (symmetric) are classified in to two types. They are triangular and band matrices. Triangular
matrices further classified as lower-left, lower-right, upper-left, and upper-right. Band matrices further
classified as diagonal matrices.

Exercise:
1. Suppose, an array A[-5 . 44] is stored in a memory whose starting address is 459. Assume that the
word size for each element is 2. Then obtain the following:
(a)How many numbers of elements are there in the array A?
(b)If one word of the memory is equal to 2bytes, then how much memory is required to store
the entire array?
(c)What is the location for A?
(d)What is the location of the 10th element?
(e)Which element is located at 465?
2. In the algorithm SearchArray discussed above, we assumed that the elements were randomly
distributed. Modify the algorithm to give a faster algorithm when the elements are already in sorted
(either ascending or descending) order.
3. The algorithm InsertArray only checks the last element for vacancy. But an array may be empty from
any i th position (L <=I <=U), in that case the numbers of push down can be reduced instead of pushing
down the entire trailing part. Modify the above algorithm InsertArray when the last element is at the ith
location (i<=U).
4. Modify the algorithm Merge if either A1 is empty or A2 is empty.
5. Suppose, we want to store records of all students in a class. The record structure is given by
Students(Roll
No:Alphanumeric,
Mark1:Numeric,Mark2:Numeric,Mark3:Numeric,Total:Numeric,
M. Nagaraju, SCSE, VIT Vellore

Page 31

If the sequential storage of records is not an objection, then we can store the records by maintaining 6
arrays whose size is specified by the total number of students in the class. Perform the following
operations.
i)List all records on the display screen
ii)Search for a particular record whose Roll No. is say, X
iii)Delete a record whose Roll No. is say, X
iv)Insert a new record whose Roll No. =X
v)Sort all the records according to the descending order of TOTAL
6. Some more programs on passing 1D array as parameter to a function
1)
Reverse the array by passing array variable as parameter to function reverse()
2)
Sort array of elements by passing array variable as parameter to function sort()
3)
Search for a particular element in an array by passing array variable as parameter to function
search()
7. Some more programs on passing 2D array as parameter to a function
i)
Find the transpose of a matrix by passing 2D array variable as parameter to function transpose()
ii)
Find the addition / subtraction of two matrices by passing 2D array variables as parameter to
iii)
Find the trace of a matrix by passing 2D array variable as parameter to function trace()
8. Define sparse matrix. List out few examples of it.

4. Structure
4.1 Definition: It is a concept that groups data items of different data types under single name. Each
such data item of structure is also known as member of a structure. To make use of structure concept in
programs one has to do three things as given below

4.1.1 structure template definition and its variable declaratiuon: It is done using a keyword struct.
The syntax is below
struct <tag_name>{
<data_type> member1;
<data_type> member2;
.
.
} variable1, variable2;
Example:
struct country{
char name;
int population;
char category;
char language;
}India, Russia, Japan, German;

M. Nagaraju, SCSE, VIT Vellore

Page 32

4.1.2 another way of structure variable declaration: Its syntax is as shown below
struct <structure_tag_name> variable1, variable2;
Example:
struct country India, Russia, Japan, German;
4.1.3 accessing members of a structure using dot operator: Its syntax is as given below
structure_variable_name . member_name;
Example:
India.name
India.population
India.category
India.language

4.2 Types: The following is the list of different types of structure

4.2.1 Nested structure:
A structure can be placed within another structure. Such a structure is known as nested structure. An
example for nested structure is as shown below.
Example:
struct personal_data{
char name;
struct date_of_birth{
int dd;
char month;
int yyyy;
}dob;
int salary;
char sex;
} pdata;
4.2.2 Array of structure:
Just as there can be arrays of basic types such as integers and floats, so also can there be arrays of
structures. The general construct for declaration of an array structure is as follows.
Example:
struct student_data{
char regno;
char sex;
char program;
} s;

4.2.3 Self referential structure: A structure that refers back itself is known as self referential structure.
Example:
struct student_data{
char regno;
M. Nagaraju, SCSE, VIT Vellore

Page 33

char sex;
char program;
struct student_data *next;
};

4.3 Passing structure variable as parameter to a function:

4.3.1 Passing simple structure variable as parameter to a function
It is explained by the following program. Let us make a program to display the total cost of product of a
structure product with fields pname, price and quantity using function total_cost()
#include<stdio.h>
struct product {
char pname;
int price;
int quantity;
};
void total_cost(struct product);
void main() {
struct product prod;
printf("Enter product name\n");
scanf("%s",prod.pname);
printf("Enter price of a product\n");
scanf("%d",&prod.price);
printf("Enter quantity of a product\n");
scanf("%d",&prod.quantity);
total_cost(prod);
system("pause");
}
void total_cost(struct product p1) {
printf("Product name=%s\n",p1.pname);
printf("Product price=%d\n",p1.price);
printf("Product quantity=%d\n",p1.quantity);
printf("product total-cost=%d\n",p1.price*p1.quantity);
}
4.3.2 Passing array of structure variable as parameter to a function
It is explained by the following program.
#include<stdio.h>
struct product{
char pname;
int price;
int quantity;
};
M. Nagaraju, SCSE, VIT Vellore

Page 34

void total_cost(struct product p,int );

void main(){
struct product prod;
int i,n;
printf("Enter number of products\n");
scanf("%d",&n);
for(i=0;i<n;i++) {
printf("Enter product name\n");
scanf("%s",prod[i].pname);
printf("Enter price of a product\n");
scanf("%d",&prod[i].price);
printf("Enter quantity of a product\n");
scanf("%d",&prod[i].quantity);
}
total_cost(prod , n);
system("pause");
}
void total_cost(struct product p1, int m){
int i;
for(i=0;i<m;i++) {
printf("Product name=%s\n",p1[i].pname);
printf("Product price=%d\n",p1[i].price);
printf("Product quantity=%d\n",p1[i].quantity);
printf("prod total-cost=%d\n",p1[i].price*p1[i].quantity);
}
}
Recollect some more programs done on structure in subject CSE101 of semester I

Exercise:
1. How is a structure different from an array?
2. What are member, tag, and variable name in a structure and what purpose do they serve?
3. What is the difference between structure tag and a structure instance?
4. How will simple structure variable and array of structure variable be passed as parameter to a function?
5. What does it mean by nested structure and self referential structure? Illustrate them with suitable
examples.
6. Explain the concept of array of structure with suitable example.

M. Nagaraju, SCSE, VIT Vellore

Page 35

5. Storage Classes:
In C, the variables are declared by the type of data they can hold. The name of a variable is associated
with a memory location within the computer where the value assigned to the variable is stored in the
form of bits. During the execution of the programs, these variables may be stored in the registers of the
CPU or the memory of the computer. To indicate where the variables would be stored, how long they
would exist, what would be their region of existence, and what would be the default values, C provides
four storage class specifiers that can be used along with the data type specifiers in the declaration
statement of a variable. These four storage class specifiers are automatic, static, external, and register.
The storage class specifier precedes the declaration statement for a variable. The general form of the
variable declaration statement that includes the storage class specifier is given as follows:
<storage class specifier> <data type> <variable name>;
Storage class specifier is used to specify mainly two things
1. scope of a variable.
2. life time of a variable.
5.1 Scope of a variable:
It is the region of program over which a variable is actually available for use.
5.2 Life time of a variable:
It specifies how long a variable retains its content or alive in a program.
5.3 Automatic Storage Class Variables:
i)
Local to a function and hence called as local variables
ii)
Scope == > within the function in which it is declared
iii)
Life time == > Till the end of the function in which it is declared
iv)
Gets initialized every time the control enters the function in which it is declared.
v)
These variables contain garbage by default
vi)
If storage class of a variable is not specified, by default it is considered as automatic
vii)
Automatic storage class is specified by the keyword auto
The following program illustrates the concepts of automatic storage class variables
Program:
void fun1();
void main(){
fun1();
fun1();
fun1();
}
void fun1(){
int x=0;
/* Storage class of x is not specified. By default it is considered as auto */
/* or we can declare it as auto int x=0 */
printf(%d\n,x++);
}
M. Nagaraju, SCSE, VIT Vellore

Page 36

Output:
0
0
0
Explanation:
Since automatic storage class variable gets initialized every time the function is called. Thus for every call
to fun1() displays 0.
5.4 External Storage Class Variables:
i)
ii)
iii)
iv)
v)
vi)
vii)

These variables are global variables.

Scope
==
>
Throughout the program.
Life time
==
>
Throughout the program.
Gets initialized only once.
Default their contents will be either zero or null once declared.
The keyword that is used with these type of variables is extern.
If both global and local variables have the same name then local variable will
get priority over the global one.

The following program illustrates the concepts of external variables

Program:
int x=10; /* Global or External variable */
void main()
{
extern int y=20;
int x=40; /* Both local and global variables have the same name.
Then local variable will have the priority over global one */
printf( x=%d\n, x); /* local variable x value gets printed */
printf(y=%d\n,y);
printf(z=%d\n,z); /* Local to fun1(). To make it global precede its declaration by extern in
function fun1() */
}
void fun1(){
extern int z=30;
printf(x=%d\n,x); /* global variable x value get printed */
printf(y=%d\n,y); /* Local to main(). To make it global precede its declaration
by extern in function main() */
printf(z=%d\n,z);
}
Output and Explanation:
40 (Local x value gets printed instead global x value)
20
30
10 (Global x value gets printed)
M. Nagaraju, SCSE, VIT Vellore

Page 37

20
30
5.5 Static Storage Class Variables:
i)
It can be either local or global.
ii)
Scope == > within the function in which it is declared.
iii)
Gets initialized only once.
iv)
Life time == > variable retains its values throughout the program.
v)
Static storage class is specified by the keyword static.
The following program illustrates the concepts of static storage class variable
Program:
void fun1();
void main()
{
fun1();
fun1();
fun1();
}
void fun1(){
static int x=0;

/* Storage class of x is static and so gets initialized only once during the
first call. During subsequent calls the variable retains its previous value
*/

printf(%d\n,x++);
}
Output:
0
1
2
Explanation:
Since static storage class variable gets initialized only once during the first call to the function fun1(). In
subsequent calls to fun1() the variable retains its previous value. Thus the output will be 0 1 and 2
Note: Static variables can be either local or global.
5.6 Register Storage Class Variables:
i)
Stored in register rather than in memory
ii)
Accessing is so fast
iii)
Very frequently used variables are stored in registers
iv)
The syntax is as below
register int count;
v)
Initialized by some garbage value by default

M. Nagaraju, SCSE, VIT Vellore

Page 38

Exercise:
1, Each storage class specifies _____________ and _____________ of a variable.
2. Static storage class can be either local or global. State whether the given statement is true or false.
3. Static variables get initialized with zero or null by default. State whether the given statement is true or
false.
4. Global variables belong to _________________ storage class.
5. Static variables get initialized only once. State whether the given statement is true or false.
6. The default storage class of a variable is _________________
7. Automatic variables get initialized only once. State whether the given statement is true or false.
8. Define the terms scope and life time of a variable in a program.
9. if a program has the same name for global and local variables, then _________ variable will get
priority over _____________ variable.
10. Automatic storage class variable is known as _____________ variables.
6 Recursion:
6.1 Definition: A concept by which a function calls itself repeatedly finite number of times to
6.2 Recursive version each problem will have two cases:
a)
Base case
b)
General case
Note: 1) Recursive programs get halted either encounters base case or memory gets exhausted finally
2) In recursive programs stack data structure is used to store each function call details,
parameter, variables and their contents, intermediate results and so on.
6.3 Recursion Vs Iteration:
______________________________________________________________________________
Recursion
Iteration
1) Code looks so simple and compact

2) Slow execution due to creation of stack,

pushing and popping the details of
each function call from the stack,
pushing and popping intermediate results from
the stack and so on issues.

2) Execution fast

3) Needs no extra memory

Iterative programs are more efficient than its recursive counterpart as the maintenance of stack is not
needed in iterative programs.

Page 39

1.
2.
3.
4.
5.

Recursive Version of Factorial

Recursive Version of Fibonacci series
Recursive Version of GCD ( Greatest Common Divisor)
Recursive Version of Sum of the digits of a 5-digit number
Recursive Version of Reverse a 5-digit number

6.4.1 Recursive version of Factorial:

factorial(n)

=
=
=

0
1
n * factorial(n-1)

If n<0 or n=0
if n=1
if n>1

(base case)
(base case)
(general case)

Program:
#include<stdio.h>
#include<conio.h>
int factorial(int);
int main()
{
int n, result;
printf(Enter an integer\n);
scanf(%d, &n);
result=factorial(n);
printf(Factorial of %d is %d\n, n, result);
getch(); return 0;
}
int factorial(int n)
{
if(n<=0) return 1;
else if(n==1) return 1;
else return n * factorial(n-1);
}
Note: Showing the working of above program diagrammatically:
Refer class notes
6.4.2 Recursive version of Fibonacci Series:
fibo(n)

=
=

0
1

if n=0
if n=1
(above two are base cases
i.e., fibo(n) =n in base case)

fibo(n-2) + fibo(n-1)

if n>1
(general case)
where n number of terms in the Fibonacci series
M. Nagaraju, SCSE, VIT Vellore

Page 40

Program:
#include<stdio.h>
#include<conio.h>
int fibo(int);
int fibo(int n)
{
if(n==0 || n==1) return n;
else return fibo(n-2) + fibo(n-1);
}
void main()
{
int n,i;
printf(Enter number of terms in the series\n);
scanf(%d,&n);
for(i=0;i<n;i++)
printf(%d, fib(i));
getch();
}
Note: Showing the working of above program diagrammatically:
Refer class notes

6.4.3 Recursive version of GCD(Greatest Common Divisor) :

gcd(a,b)

=
=

b
gcd(b, a%b)

if (a%b ==0)
otherwise

(base case)
(general case)

Program:
#include<stdio.h>
#include<conio.h>
int a,b;
int gcd(int, int);
void main(){
printf(Enter two integer numbers\n)
scanf(%d%d, &a,&b);
printf(The GCD of %d and %d is %d\n, a, b, gcd(a,b));
getch();
}
int gcd(int a, int b){
if(a % b = = 0) return b;
else return gcd(b, a % b);
}
Working of the above program:
Let us consider two numbers 18 and 48. Take a=18 and b=48
Find a % b = 18 % 48 =18 which is not equal to zero, So go to else part and execute gcd(48,
M. Nagaraju, SCSE, VIT Vellore

Page 41

18)
Find 48 %18 = 12. As remainder is not zero, so go to else part and execute gcd(18,12)
Find 18 % 12 = 6. As remainder is not zero, so go to else part and execute gcd(12,6)
Find 12%6=0. As remainder is zero, so 6 will be the gcd of given numbers 18 and 48.
6.4.5 Recursive version of sum of digits and reverse of 5-digit number:
Program:
#include<stdio.h>
#include<conio.h>
int rsum(int);
int rrev (int);
void main(){
int num;
printf(Enter non-zero 5-digit number\n);
scanf(%d, &num);
printf(Sum=%d\t and Reverse=%d\n, rsum(num), rrev(sum));
getch();
}
int rsum(int num){
static int sum=0;
int digit;
digit = num % 10;
sum = sum + digit;
num = num / 10;
if(num !=0)
rsum(num);
return sum;
}
int rrev(int num){
static int rev =0;
int digit;
digit = num % 10;
rev = rev *10 + digit;
num = num / 10;
if(num!=0)
rrev(num);
return rev;
}
Output
123
Sum = 6 Reverse=321

M. Nagaraju, SCSE, VIT Vellore

Page 42

Exercise:
1. Why recursive version of a program is less efficient than its iterative counterpart?
2. Every recursive version of a program will have ______________ and ________________ cases.
3. Recursive program terminates if it encounters either _____________ or _________________.
4. What data structure is used in recursive version of a program?
5. Recursive version of a program requires _________ number of lines of code than its iterative counterpart.

M. Nagaraju, SCSE, VIT Vellore

____________________________________

Page 43