You are on page 1of 55

# Programming Fundamentals

ER/CORP/CRS/LA06/003 1
Session Plan
• Introduction to Data Structures

• Introduction to Arrays

## • Arrays and Functions

• Introduction to Strings

## • Handling Multidimensional Arrays

Infosys Technologies Ltd Version no: 2.0

## Today's session we will be discussing the various data structures

ER/CORP/CRS/LA06/003 2
Data structure

•Data Struture
•is the logical or mathematical model of a particular organization of data
• mirror the actual relationships of the data

## Examples of data structures:

•Arrays
•Stacks
•Queues
•trees c

Infosys Technologies Ltd Version no: 2.0

Data structures are "an organization of information, usually in memory, for better algorithm
efficiency."1 Examples of data structures are arrays, queues, dictionaries, hash tables, and
collections. The key component of this definition is related to "algorithm efficiency." What
does a data structure have to do with algorithm efficiency? As you will see in this set of
articles, plenty. Arrays serve as a good starting point for demonstrating how data structure
choice affects algorithm choice, and vice versa
The logical or mathematical model of a particular organization of data is called a data
structure. While solving a programming problem, once the algorithm has been developed,
the next step is to determine the data structures to be used to implement the algorithm. Two
things should be considered in selecting a data structure.
1. The structure should mirror the actual relationships of the data in the real world.
2. The structure should be simple so that processing data is effective.

Data structure are classified as either linear or nonlinear. A data structure is said to be
linear if its data have a linear relationship. One way of achieving the linear relationship in a
data structure is to represent the data in sequential memory locations. These linear
structures are called arrays.

ER/CORP/CRS/LA06/003 3
Data structure.. contd...

– Example:
– Arrays
– Lists
– Stacks
– strings

##  A data structure is nonlinear if its elements are accessed through

different directions
– Example:
– Trees : Are used to represent data containing a hierarchical relationship
between elements

Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 4
How to select a data structure?

##  Two things should be considered in selecting a data structure

– The structure should mirror the actual relationships of the data in the real
world.

## – The structure should be simple so that processing data is effective.

Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 5
Arrays

##  The linear relationships between the elements is represented by means of

sequential memory locations.

Infosys Technologies Ltd Version no: 2.0

A very familiar concept to most any programmer is that of an array, and they are a common part of our everyday
programming lives. We use them so often that we probably forget what they really are. Arrays are a data structure that
is used to store a group of objects of the same type sequentially in memory. All the elements of an array must be the
same data type.
Arrays are "a set of items which are randomly accessible by numeric index." Arrays are typically laid out in memory as
a contiguous chunk of blocks, where each block is of the same data type. Because the memory is laid out as a
contiguous set of memory chunks, arrays are very fast for accessing items by index. Arrays are a great choice of data
structure when the number of elements it contains is known ahead of time.
An array is a fixed collection of same data-type that are stored contiguously and are accessible by an index. What this
means is that an array consists of a set of physically contiguous memory locations. These memory locations can all be
addressed with one name – the name of the array. Each location in the array is referred to by the subscript of the
array. In C, the syntax to declare an array is as follows.
int aiArrayOfIntegers[10];
This statement declares an integer array named aiArrayOfIntegers, consisting of 10 elements. Each of these 10
elements can only contain an integer value. The index of the first element of an array in C is 0. That is, the ten
elements of the array can be referenced as
aiArrayOfIntegers[0], aiArrayOfIntegers[1], aiArrayOfIntegers[2], ... , aiArrayOfIntegers[9].
These values may be accessed as shown below.
iVar1 = aiArrayOfIntegers[0];
Note that in the declaration statement, aiArrayOfIntegers[10]means that there are 10 elements in the array; but in an
assignment statement, aiArrayOfIntegers[10]refers to the 11th element of a 10-element array. That is, if there are ten
elements in an array, the subscript of the last element of the array is 9, and not 10. This is a common programming
mistake and results in some indeterminate value being returned by aiArrayOfIntegers[10], which is very likely to cause
program failure.
In the declaration statement, the subscript can be a named constant; however, it cannot be a variable.

ER/CORP/CRS/LA06/003 6
Example
• Read the marks of 2 subjects; find their average; print the marks of that subject
as queried by user.

Infosys Technologies Ltd Version no: 2.0

## write the program.

#include <stdio.h>
int main()
{
int iMark1, iMark2, iNumber;
float fAverageMarks;
printf("\nEnter marks for the subject1 : ");
scanf("%d", &iMark1);
printf("\nEnter marks for the subject2 : ");
scanf("%d", &iMark2);
fAverageMarks = (iMark1 + iMark2) / 2.0;
printf("\nAverage is: %f", fAverageMarks);
printf("\nEnter subject number whose marks you want");
scanf("%d", &iNumber);
if (iNumber == 1)
printf("\nMarks of subject 1 is: %d", iMark1);
else if (iNumber == 2)
printf("\nMarks of subject 2 is: %d", iMark2);
else
printf("\nInvalid Number");
}

ER/CORP/CRS/LA06/003 7
Array
• Sequence of elements

ARRAY

In d iv id u a l :
d a ta o b je c ts :
o f id e n tic a l
n a tu re
:
: :
: :
:

• Indexing
– Store an element
– Retrieve an element

Infosys Technologies Ltd Version no: 2.0

Now lets try and extend the previous problem to accepts marks in five subjects for a student and display the average. It should then be
able to display marks for any subject that the user wants.
Consider solving this problem without the use of arrays.
#include <stdio.h>
main()
{
int iMark1;int iMark2;int iMark3;int iMark4;int iChoice;
float fAverage;
printf("\n Enter the four marks");
scanf("%d%d%d%d",&iMark1,&iMark2,&iMark3,&iMark4);
fAverage = (iMark1 + iMark2 + iMark3 +iMark4)/4.0;
printf("\n Average mark is %f", fAverage);
printf("\n Do you want to see the Mark ?”);
printf("\n 1. Mark1");
printf("\n 2. Mark2");
printf("\n 3. Mark3");
printf("\n 4. Mark4");
scanf("%d", &iChoice);
switch (iChoice){
case 1: printf("\n Mark1 = %d", iMark1); break;
case 2: printf("\n Mark2 = %d", iMark2); break;
case 3: printf("\n Mark3 = %d", iMark3); break;
case 4: printf("\n Mark4 = %d", iMark4); break;
}

ER/CORP/CRS/LA06/003 8
Array -Contd..)
• Please refer to Notes page for more explanation on previous slide

Infosys Technologies Ltd Version no: 2.0

## Consider the Previous program written using array.

An array is defined with this syntax.
datatype arrayName[size];
int ID[30]; /* Could be used to store the ID numbers of students in a class */
float temperatures[31]; /* Could be used to store the daily temperatures in a month */
unsigned short int[52]; /* Holds 52 unsigned short integer values */
#include <stdio.h>
main()
{
int aiMarksArray[4];
int iChoice;
int Counter;
int iSum;
iSum = 0;
iChoice = 0;
printf("\n Enter the five marks");
fflush(stdin);
for (Counter = 0; Counter < 4; Counter = Counter + 1)
{
scanf("%d ", &aiMarksArray[Counter]);
iSum = iSum + aiMarksArray[Counter];
}
printf("\nAverage mark is %f", iSum/4.0);
do
{
printf("\n Do you want to see the Mark ?”);
printf("\n 1. Mark1");
printf("\n 2. Mark2");
printf("\n 3. Mark3");
printf("\n 4. Mark4");
fflush(stdin);
scanf("%d", &iChoice);
}while (iChoice < 1 || iChoice > 4);
printf("\n Mark%d = %d",iChoice, aiMarksArray[iChoice-1]);
}

ER/CORP/CRS/LA06/003 9
Array-(Contd..)
• Please refer to Notes page for more explanation on previous slide

Infosys Technologies Ltd Version no: 2.0

Note how the use of an array makes input, processing and output easier. Since an array
consists of physically contiguous elements that can all be addressed using the name of the
array and a subscript, manipulating the values in an array is not only more efficient, it is also
more intuitive compared to working with a number of independent variables.
When you declare an array, you declare the type of data it will hold and the size of the
array. Once the memory for the array is allocated, it cannot be changed. If you want to set
the value for an item in the array, you reference a pre-existing index in the array and specify
its contents.If you want to increase the size of the array, you must create a new array with
size n+1 and copy the contents of the old array into the new one

ER/CORP/CRS/LA06/003 10
Example
• Read the marks of students in a class and then print the number of students for
each possible total marks.
• marks are in the range 0 -- 100

Infosys Technologies Ltd Version no: 2.0

Using Arrays
Arrays in C are zero based. Suppose an array named myExample contains N elements. This array is indexed from 0
to (N-1). The first element of myExample is at index 0 and is accessed as myExample[0]. The second element is at
index 1 and is accessed as myExample[1]. The last element is at index (N-1) and is accessed as myExample[N-1]. As
a concrete example, suppose N equals 5 and that myExample will store integer data.
int myExample[5]; /* Defines myExample to be of length 5 and to contain integer data */
myExample[0] /* First element of myExample */
myExample[1] /* Second element of myExample */
myExample[2] /* Third element of myExample */
myExample[3] /* Fourth element of myExample */
myExample[4] /* Fifth and final element of myExample */

Here is a sample program that calculates and stores the squares of the first one hundred positive integers.
#include <stdio.h>
int main()
{
int square[100];
int i; /* loop index */;
int k; /* the integer */

## /* Calculate the squares */

for (i = 0; i < 100; i++) { k = i + 1; /* i runs from 0 to 99 , k runs from 1 to 100 */
square[i] = k*k;
printf("The square of %d is %d\n",k,square[i]);
}
return 0;
}

ER/CORP/CRS/LA06/003 11
Solution
#include <stdio.h>
int main( )
{
int aiArrHist[101];
int iSize;
int iCount;
int iMarks;

## printf("How many students are there?");

scanf("%d", &iSize);

## for(iCount = 0; iCount < 101; iCount++)

iArrHist[iCount] = 0;

Infosys Technologies Ltd Version no: 2.0

## •You cannot initialize an array using a variable.

For example: int x = 5; int ia[x]; This above example is illegal.
•C restricts the array initialization size to be constant. So is this legal? int ia[]; No. The array
size is not known at compile time. How can we get around this? By using macros we can
also make our program more readable! #define MAX_ARRAY_SIZE 5 /* .... code .... */ int
ia[MAX_ARRAY_SIZE]; Now if we wanted to change the array size, all we'd have to do is
change the define statement!
•We can initialize the contents of the array
int ia[5] = {0, 1, 3, 4};
int ia[ ] = {0, 2, 1};
Both of these work. The first one, ia is 20 bytes long with 16 bytes initialized to 0, 1, 3, 4.
The second one is also valid, 12 bytes initialized to 0, 2, 1.

## Arrays are static memory allocated data structures.

ER/CORP/CRS/LA06/003 12
Solution –(contd…)
for(iCount = 0; iCount < iSize; iCount++)
{
scanf("%d", &iMarks);
aiArrHist[iMarks] = aiArrHist[iMarks] + 1;
}
for(iCount = 0; iCount < 101; iCount++)
printf("\nThe no. of students with marks %d are %d", iCount,
aiArrHist[iCount]);
}

Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 13
Example
• Insert a element in the array

Infosys Technologies Ltd Version no: 2.0

#include <stdio.h>
void fvAcceptArrValues(int [],int);
void fvInsArrElement(int aiArrData[],int iPos,int iNoOfElements,int iNewNumber);
void fvDispArr(int aiArrData[],int iNoOfElenents);
int iCount;
int main( )
{
int aiArrData[100];
int iNoOfElementsInArray;
int iNewNumber;
int iPos;
printf("How many numbers are there ");
scanf("%d", &iNoOfElementsInArray);
fvAcceptArrValues(aiArrData,iNoOfElementsInArray);
printf("Enter the new number ");
scanf("%d", &iNewNumber);
printf("Where do you want to insert");
scanf("%d", &iPos);
fvInsArrElement(aiArrData,iPos,iNoOfElementsInArray,iNewNumber)
printf("The new data is:");
fvDispArr(aiArrData,iNoOfElementsInArray);
}

ER/CORP/CRS/LA06/003 14
Inserting Elements - Solution

## printf("How many numbers are there ");

scanf("%d", &iNoOfElementsInArray);
fvAcceptArrValues(aiArrData,iNoOfElementsInArray);
printf("Enter the new number ");
scanf("%d", &iNewNumber);
printf("Where do you want to insert");
scanf("%d", &iPos);
fvInsArrElement(aiArrData,iPos,iNoOfElementsInArray,iNewNumber);
printf("The new data is:");
fvDispArr(aiArrData,iNoOfElementsInArray);

Infosys Technologies Ltd Version no: 2.0

Like simple value and variable , it is also possible to pass the value of an array element and even an entire
array as an argument to a function. To pass an array element to a function, the array element is specified as
an argument to the function in the normal fashion. Let us revisit our earlier example of finding average marks
for student. We rewrite the example using the array variable.
#include <stdio.h>
float fGetAverage (int iNum1, int iNum2, int iNum3);
void main(){
int i; int aiArray[3]; float fAverage;
for (i = 0; i < 3; i++)
scanf("%d", &aiArray[i]);
fAverage = fGetAverage(aiArray[0], aiArray[1], aiArray[2]);
printf("Average is %f", fAverage);
}
float fGetAverage (int iNum1, int iNum2, int iNum3)
{ float fAvg;
fAvg = (iNum1 +iNum2 +iNum3) /(3.0);
return fAvg;
}

ER/CORP/CRS/LA06/003 15
Inserting Elements – Solution-(Contd..)
• Please refer to Notes page for more explanation on previous slide

Infosys Technologies Ltd Version no: 2.0

In the above example, we have passed the array elements in the same fashions as we did for simple variables in
our earlier example However, the above example can also be written more succinctly as shown below by passing
the whole array to the function fGetAverage instead of passing each element of the array separately.
#include <stdio.h>
#define SIZE 3
float fGetAverage (int aiArr[], const int N);
void main()
{
int i;

int aiArray[SIZE];
float fAverage;

## printf(" Please enter %d numbers",SIZE);

fflush(stdin);
for (i = 0; i < SIZE; i++)
scanf("%d", &aiArray[i]);

fAverage = fGetAverage(aiArray,SIZE);
printf("Average is %f", fAverage);
}
float fGetAverage (int aiArr[], const int N)
{
int iSum;
int i;
float fAvg;
iSum = 0;
for (i = 0; i < N; i++)
iSum = iSum + aiArr[i];
fAvg = iSum /(3.0);
return fAvg;
}

ER/CORP/CRS/LA06/003 16
Inserting Elements – Solution-(Contd..)
• Please refer to Notes page for more explanation on previous slide

Infosys Technologies Ltd Version no: 2.0

Observe the prototype declaration, function definition and function call for
fGetAverage in the above program. For passing an entire array to a function, it is only
required to list the name of the array, without any subscript, in the function call. In the
function prototype and definition there is no mention about the size of the array.

ER/CORP/CRS/LA06/003 17
Inserting Elements – Solution-(Contd..)
• Please refer to Notes page for more explanation on previous slide

Infosys Technologies Ltd Version no: 2.0

However, there is a major distinction that must always be kept in mind while dealing with
array arguments. Before discussing further let us look at the following simple example.
Consider an array of integers of size 10. We initialize all the elements of the array to 0.
Then we change the value of those array elements to 1 who are occupying the even position
in the array, i.e., with index 1, 3 5, 7, 9. Finally, print all the elements of the array after re-
initialization.
The program can be written as below.
#include <stdio.h>
# define SIZE 10
main( )
{
int i;
int aiArray[SIZE];
for (i = 0; i < SIZE; i++)
aiArray[i] = 0; //initialization
for (i = 0; i < SIZE; i++)
{
if ( i %2 != 0)
aiArray[i] = 1; //re-initialization
}
for (i = 0; i < SIZE; i++)
printf(“ array[%d] = %d \n “, i, aiArray[i] );
}

ER/CORP/CRS/LA06/003 18
Inserting Elements – Solution-(Contd..)
• Please refer to Notes page for more explanation on previous slide

Infosys Technologies Ltd Version no: 2.0

Let us rewrite the above example using a self-explanatory function where the entire array has been passed in the
argument.
#include <stdio.h>
# define SIZE 10
void vRe_initialize( int aiArr[], int n)
{
int i;
for (i = 0; i < n; i++)
{
if ( i %2 != 0)
aiArr[i] = 1;
}
}
main( )
{
int i;
int aiArray[SIZE];
for (i = 0; i < SIZE; i++)
aiArray[i] = 0; //initialization
vRe_initialize(aiArray, SIZE);
for (i = 0; i < SIZE; i++)
printf(“array[%d] = %d \n”, i, aiArray[i]);
}
The output of the above program after its execution demonstrates one major deviation from what we have been
seeing so far. That is, the function vRe_initialize changes the value of the original array aiArray that has been
passed to it as argument. This change remains in effect even after the function
vRe_initialize has completed its execution and has returned to the calling routine (i.e., main( ))
The following points have to be kept in mind when dealing with array arguments.
· In a function call (in C language), the values that are passed as arguments to the function are copied (known
as Pass by value) into the formal parameters.
·

ER/CORP/CRS/LA06/003 19
Inserting Elements – Solution-(Contd..)
• Please refer to Notes page for more explanation on previous slide

Infosys Technologies Ltd Version no: 2.0

· However, when the entire array is passed as arguments, the entire contents of the
array are NOT copied into the formal parameter array of the function. Instead, the formal
parameter array holds the information describing WHERE in the computer’s memory the
actual array is located (known as Pass by Reference). Thus, any changes made to the
formal parameter array by the function are reflected on the actual array passed to the
function. Hence, when the function returns, the changes still remain in effect.
Note: The preceding discussion applies only to the entire arrays that are passed as
arguments, and not to the individual elements, whose values are copied into the
corresponding formal parameters and therefore cannot be changed by the function.

ER/CORP/CRS/LA06/003 20
Inserting Elements – Solution-(Contd…)
void fvAcceptArrValues(int aiArrData[],int iNoOfElementsInArray)
{ for(iCount = 0; iCount < iNoOfElementsInArray; iCount++)
scanf("%d", &aiArrData[iCount]);
}
void fvInsArrElement(int aiArrData[],int iPos,int iNoOfElementsInArray,int
iNewNumber)
{ for(iCount = iNoOfElementsInArray - 1; iCount >= iPos-1; iCount--)
aiArrData[iCount+1] = aiArrData[iCount];
aiArrData[iPos -1] = iNewNumber;iNoOfElementsInArray = iNoOfElementsInArray +1;
}
void fvDispArr(int aiArrData[],int iNoOfElementsInArray)
{ for(iCount = 0; iCount < iNoOfElementsInArray; iCount++)
printf("%d",aiArrData[iCount]);
}

Infosys Technologies Ltd Version no: 2.0

When an array is passed into a function, the function receives not a copy the array, but
instead the address of the first element of the array. The function receives a pointer to the
start of the array. Any modifications made via this pointer will be seen in the calling
program. Let's see how this works. Suppose the main program has an array of 10 integers
and that a function has been written to double each of these.
void doubleThem(int a[], int size);
int main()
{
int myInts[10] = {1,2,3,4,5,6,7,8,9,10};
doubleThem(myInts, 10);
return 0;
}
void doubleThem(int a[], int size)
{
int i;
for (i = 0; i < size; i++)
{
a[i] = 2 * a[i];
}
}
Hence entire Arrays are passed by reference by default. But when individual array
elements are passed as argument they could be passed by ref / by argument.

ER/CORP/CRS/LA06/003 21
Inserting Elements – Solution-(Contd…)
• Please refer to Notes page for more explanation on previous slide

Infosys Technologies Ltd Version no: 2.0

## Consider another example

#include <stdio.h>
#include <stdio.h>
void fvChange(int aiArr1[],int aiArr20,int *aiArr21);
main()
{
int aiArr1[2],aiArr2[2];
aiArr1[0]=1;
aiArr1[1]=2;
aiArr2[0]=3;
aiArr2[1]=4;
printf("Arr1 Elements %d-%d",aiArr1[0],aiArr1[1]);
printf("\nArr2 Elements %d-%d",aiArr2[0],aiArr2[1]);
printf("\n");
fvChange(aiArr1,aiArr2[0],&aiArr2[1]);
printf("Arr1 Elements %d-%d",aiArr1[0],aiArr1[1]);
printf("\nArr2 Elements %d-%d",aiArr2[0],aiArr2[1]);
}
void fvChange(int aiArr1[],int aiArr20,int *aiArr21)
{
aiArr1[0]=5;
aiArr1[1]=6;
aiArr20=7;
*aiArr21=8;
}
In the example aiArr1 array is passed by reference,aiArr2[0] element is passed by value and aiArr2[1] element is
passed by reference.

ER/CORP/CRS/LA06/003 22
Arrays and Pointers

## int ia[6] = {0, 1, 2, 3, 4, 5};

int *ip;
ip = ia; /* equivalent to ip = &ia[0]; */
ip[3] = 32;

ia 100

## ia[0] ia[1] ia[2] ia[3] ia[4] ia[5]

ip 100

Infosys Technologies Ltd Version no: 2.0

•An array name is just a pointer to the beginning of the allocated memory space.
•Let's take this example and analyze it:
int ia[6] = {0, 1, 2, 3, 4, 5}; /* 1 */
int *ip; /* 2 */
ip = ia; /* equivalent to ip = &ia[0]; */ /* 3 */
ip[3] = 32; /* equivalent to ia[3] = 32; */ /* 4 */
ip++; /* ip now points to ia[1] */ /* 5 */
printf("%d ", *ip); /* prints 1 to the screen */ /* 6 */
ip[3] = 52; /* equivalent to ia[4] = 52 */ /* 7 */
Ok, so what's happening here? Let's break this down one line at a time. Refer to the line numbers on the side:
1.Initialize ia
2.Create ip: a pointer to an int
3.Assign ip pointer to ia. This is effectively assigning the pointer to point to the first position of the array.
4.Assign the fourth position in the array to 32. But how? ip is just a pointer?!?! But what is ia? Just a pointer!
5.Use pointer arithmetic to move the pointer over in memory to the next block. Using pointer arithmetic
automatically calls sizeof().
6.Prints ia[1] to the screen, which is 1
7.Sets ia[4] to 52. Why the fifth position? Because ip points to ia[1] from the ip++ line.
Now it should be clear. Pointers and arrays have a special relationship because arrays are actually just a pointer
to a block of memory!
Point to be noted here is that Arrays are constant pointers.

ER/CORP/CRS/LA06/003 23
Coping with inflexibilities of Arrays
• define constant for size
– recompile
• define a very big array
– wastage of space

Infosys Technologies Ltd Version no: 2.0

Because names of arrays represents just a pointer to the beginning of the array, we have
some limitations or "problems."
1.No Array Out of Bounds Checking. For example: int ia[2] = {0, 1}; printf("%d ", ia[2]); The
above code would result in runtime error, because you are trying to look at an area of
memory not inside the array memory allocation.
2.Array Size Must be Constant or Known at Compile-time
3.Arrays Cannot be Copied or Compared. Why? Because they are pointers.
4.Array Index Type must be Integral.
Another limitation comes with arrays being passed into functions. Take for example: void
func(int ia[]) void func(int *ia) Both are the same declaration (you should know why by now).
But why would this cause problems? Because only the pointer to the array is passed in,
not the whole array. So what if you mistakenly did a sizeof(ia) inside func? Instead of
returning the sizeof the whole array, it would only return the size of a single element in the
array.

ER/CORP/CRS/LA06/003 24
Array as a data structure
• very fast at storing and getting from a particular index
• Slow in inserting and deleting elements
• Alternatives are there…
– trees

a
a NULL
a

## 2nd data element

Infosys Technologies Ltd Version no: 2.0

Although arrays are extremely useful, one of the major disadvantages of using an array is
insertion (deletion) of an element to (from) the array. Consider inserting an element in the
beginning of an array (assume that enough memory is available for insertion). For
achieving this, the value in every element must be moved to its subsequent element. Then
the new value is inserted into the first position. Imagine such situation when the array size
is large enough! Similar is the case for deleting an element from an array. An alternative is

A linked list(a linear data structure) consists of a series of nodes such that, each node has
a data element and the address of the next node in the list. The following figure gives a
schematic view of a link list with 5 nodes. The first node contains the information of element
1 and address of element 2, the second node contains the information of element 2 and
address of node 3 and so on. To insert or delete a new node, only two nodes at most (the
ones just before in case it is inserted after the first node and just after in case it is inserted
before the last node) have to be modified suitably.

ER/CORP/CRS/LA06/003 25
Strings
• Text processing
– word processors
• Searching
– databases
• Input/output

Infosys Technologies Ltd Version no: 2.0

## String (in C) is referred to a variable-length array of characters, defined by a starting point

and by a string-termination character (‘ \0’) marking the end. In computing applications
where processing of textual data are involved, strings are useful in representing these
textual data and hence, are valuable in low-level data structure. The difference between an
array of characters and a string revolves around length. Both represents a contiguous area
of memory, but the length of the array is set at the time that array is created, whereas the
length of a string may change during the execution of a program.

We need to reserve memory for a string, either during compile time by declaring an array of
characters (will be followed in this course) or at execution time by invoking dynamic memory
allocation function (beyond the scope of the course). Once the array is allocated, we can fill
it with characters, starting at the beginning and ending with the string termination character
(‘\0’)or popularly known as the NULL character(i.e., having value 0). Without a string
termination character, the string is same as an array of characters. Only with the string
terminating character, we can consider the portion of the array from the beginning to the
string termination character to contain meaningful information.

ER/CORP/CRS/LA06/003 26
Definitions of strings
• char name[4] =“xy”;
Will create a string consisting of 4 memory locations.
1st element stores x
2nd element stores y
3rd element stores ‘\0’;
4th element is unused
• char n1[] = “xy”;
Will create a string consisting of 3 memory locations.
1st element stores x
2nd element stores y
3rd element stores ‘\0’;
• char a[5]={'h','e','l','l','o'};
Will create a character array consisting of 5 memory locations.

Infosys Technologies Ltd Version no: 2.0

Stings in C are stored as null character, '\0', terminated character arrays. This means that
the length of a string is the number of characters it contains plus one to store the null
character. Common string operations include finding lengths, copying, searching, replacing
and counting the occurrences of specific characters and words.
A string is just a character array with the convention that the end of the valid data is marked
by a null '\0'. Now you should be able to see why you can read in a character string using
scanf("%s", name) rather than scanf("%s",&name) - name is already a pointer variable.
Manipulating strings is very much a matter of pointers and special string functions. For
example, the strlen(str) function returns the number of characters in the string str. It does
this simply by counting the number of characters up to the first null in the character array -
so it is important that you are using a valid null-terminated string. Indeed this is important
with all of the C string functions

ER/CORP/CRS/LA06/003 27
Input/output of strings
char yourName[20]

scanf("%s",yourName);

scanf(“%s”,&yourName[0]);

## /* yourName is a character array.

yourName[0] specifies the first element of the array.
&yourName[0] specifies the address of the first
element of the array. In C, an array name by itself is
shorthand for the address of the first element. So,
yourName is equivalent to &yourName[0], which is
what must be passed into scanf. */

Infosys Technologies Ltd Version no: 2.0

scanf will skip over white space such as blanks, tabs and newlines in the input stream. The
exception is when trying to read single characters with the conversion specifier %c. In this
case, white space is read in. So, it is more difficult to use scanf for single characters.
Some more input functions
getchar
getchar reads a single character from standard input. Its prototype is:

int getchar();

It returns int rather than char because the "end of file", EOF, character must be handled.
EOF is an int and is too large to fit in a char variable. A newline character in C is '\n'. This
designates the end of a line.

gets
gets reads a line of input into a character array. Its prototype is:

## char *gets(char *buffer);

It returns a pointer to the character string if successful, or NULL if end of file is reached or if
an error has occurred. The string is also read into the character array specified as an
argument. The character string will be terminated be a "\0", which is standard for C.

ER/CORP/CRS/LA06/003 28
Input/output of strings

## •printf("Hello World\n"); /* The format string contains only ordinary

characters. Ordinary characters are output unmodified.
A character string in C is of type "char *". */

## •printf("My name is %s\n",myName); /* The %s specifies that a character

string will be output. */

## •printf("My first initial is %c\n",initial); /* The %c specifies that a

character will be output. */

## •printf("Hello %s or should I say %c\n",myName,initial);

/* Multiple arguments of different types may be output. */

Infosys Technologies Ltd Version no: 2.0

putchar
putchar writes a single character to standard output. Its prototype is:
int putchar(int value);
puts
puts writes a line of output to standard output. Its prototype is:
int puts(const char *buffer);

Here is a simple program which echoes back everything that is typed in. Note that
depending on which operating system you are using, EOF is entered by typing control-z or
control-d. So, if you try running this code, type control-z or control-d to end execution

#include <stdio.h>
int main()
{
int c;
while ((c = getchar()) != EOF)
{
putchar(c);
}
return(0);
}

It terminates the line with a newline, '\n'. It will return EOF is an error occurred. It will return a
positive number on success.

ER/CORP/CRS/LA06/003 29
Input/output of strings-(Contd…)
• Please refer to Notes page for more explanation on previous slide

Infosys Technologies Ltd Version no: 2.0

Here is the "echo" program implemented using the functions gets and puts. If you run this, remember
to type control-z or control-d to end execution.

#include <stdio.h>
int main()
{
char buffer[120]; /* Holds input and output strings */
char *pt; /* A pointer to datatype char */
int returnCode;
while ((pt = gets(buffer)) != NULL)
{
returnCode = puts(buffer);
if (returnCode == EOF)
{
printf("Error on output\n");
}
}
return(0);
}

There are some very important things to note in the this example. First, gets returns a NULL pointer
when EOF is reached. This is the condition that must be checked in while loop. Second, puts returns
EOF on failure. A check is made on this, and an appropriate error message is output if an error has
occurred. Finally, the character array buffer is declared to be of length 120. The function gets makes
no check on the array size to see if it is large enough to hold the string entered. It is up to the
programmer to create a character array that is large enough. If the entered string is larger than the
array, gets will still put the string in memory starting at the location of the first byte of the designated
array. Since the string is longer than the array, the result is that memory past the end of the array will
be overwritten with the entered string. This will cause either erratic behavior or failure (core dump) of
the program.

ER/CORP/CRS/LA06/003 30
String Handling functions

There is no basic data type for a string in C. Instead, strings in C are implemented
as an array of characters. There is an extensive set of library functions for
manipulating strings available in string.h

## • Length of string strlen function

• Concatenate two strings strcat function
• Compare two strings strcmp function
• Copy a string to another strcpy function
• Next Token of string strtok function
• Replace/substitute a string
• Find substring in string

Infosys Technologies Ltd Version no: 2.0

The strlen function takes as parameter the string whose length has to be calculated and
return the number of characters (excluding ‘\0’)

The strcmp function takes 2 strings, to be compared .as parameters and does a character by
character comparison. It returns a integer value which is
0 if the strings are equal
>0 if the string 1 is greater than string 2 (ascii difference of the chars where mismatch is
found)
<0 if the string 1 is less than string 2 (ascii difference of the chars where mismatch is found)

The strcpy function takes 2 string arguments. The first parameter is the destination string
and the second parameter is the source string. Care need to be taken that the destination
string needs to be large enough to store the source string. The function does not validate
this while copying

## Some more String handling functions are listed in the slide.

ER/CORP/CRS/LA06/003 31
String Handling functions-(contd..)
• Please refer to Notes page for more explanation on previous slide

Infosys Technologies Ltd Version no: 2.0

## Functions Function Signature Description

strchr() char* strchr(const char* s, int c) Returns a pointer to the first occurrence of c in string s.
strncat() char* strncat(char* s1, const char* s2, size_t n) Tacks on the first n characters of s2 onto s1. A
pointer to s1 is returned.
strncmp() int strncmp(const char* s1, const char* s2, size_t n) Compares s1 with the first n characters of s2. Returns
a negative, zero, or positive integer (just like strcmp).
strncpy() char* strncpy(char* s1, const char*s2, size_t n) Copies the first n characters of s2 into the first n
characters of s1.
strrchr() char* strrchr(const char*s, int c) Returns a pointer to the last occurrence of c in string s.
(Compare with strchr().)
strstr() char* strstr(const char* s1, const char* s2) Returns the address of the first occurence of string s2
that is also in string s1. Returns NULL if s2 is not found
in s1.

ER/CORP/CRS/LA06/003 32
String Length Function
strlen() - Returns the number of characters in the string s, starting at s[0] and
ending before the first NULL.
Prototype declaration - size_t strlen(const char* s)
#include <stdio.h>
#include <string.h>
int main()
{
char name[80],int length;
gets(name); length = strlen(name);
printf("Your name has %d characters\n", length);
return 0;
}

Infosys Technologies Ltd Version no: 2.0

## int iStr_len(char acString[])

{
int iIndex ;
iIndex = 0;
while(acString[iIndex] != ‘\0’)
iIndex++;
return iIndex;
}

ER/CORP/CRS/LA06/003 33
String Compare Function
strcmp() - Compares s1 and s2 alphabetically. Returns a negative, zero, or
positive number depending on whether s1 is before, the same as, or after s2 if
you were alphabetizing s1 and s2.
Prototype declaration - int strcmp(const char* s1, const char* s2)

#include <stdio.h>
#include <string.h>
void main()
{ char first[80], second[80];
printf("Enter a string: "); gets(first);
printf("Enter another string: "); gets(second) ;
if (strcmp(first, second) == 0) /* comparison of the form if(first==second) is not valid*/
puts("The two strings are equal");
else puts("The two strings are not equal"); return 0;
}
Infosys Technologies Ltd Version no: 2.0

## The strcmp Function

The strcmp function is used to compare two strings together. The variable name of an array
points to the base address of that array. Therefore, if we try to compare two strings using the
condition if (first == second) We would be comparing two addresses, which would obviously
never be the same as it's not possible to store two values in the same location.

## Code the user defined version of the same function.

ER/CORP/CRS/LA06/003 34
String Copy Function
strcpy() - Copies s2 into s1, and returns a point to s1.
Prototype declaration - char* strcpy(char* s1, const char* s2)

#include <stdio.h>
#include <string.h>
void main()
{
char first[80], second[80];
printf("Enter a string: "); gets(first);
strcpy(second, first); /* an assignment of the form second=first is invalid */
printf("first: %s, and second: %s\n", first, second);
return 0;
}

Infosys Technologies Ltd Version no: 2.0

## The strcpy Function

The strcpy function is used to copy one string to another.
Examples
firstname= "Arnold"; /* Illegal */
strcpy(firstname,”Arnold”) ; /* valid */
lastname= "Schwarznegger"; /* Illegal */
strcpy(lastname,”Schwarznegger”) ; /* valid */

ER/CORP/CRS/LA06/003 35
String Concatenate Function
strcat() - Adds string s2 onto the end of s1 (conCATenation).
Prototype declaration - char* strcat(char* s1, const char* s2)

#include <stdio.h>
#include <string.h>
void main()
{
char first[80], second[80];
printf("Enter a string: "); gets(first);
printf("Enter another string: "); gets(second);
strcat(first, second); /* adding using first=first+second */ is invalid */
printf("The two strings joined together: %s\n", first); return 0;
}

Infosys Technologies Ltd Version no: 2.0

## The strcat Function

The strcat function is used to join one string to another.
Exmaple
fullname= "Mr"+firstname +lastname; /* Illegal */
strcat(fullname,”Mr”);
strcat(fullname,firstname);
strcat(fullname,lastname);

ER/CORP/CRS/LA06/003 36
String Tokenizer function
strtok() - to find the next token in a string
Prototype declaration - char* strcat(char* s1, char* s2)

#include <stdio.h>
#include <string.h>
void main()
{
char line[80], char *delimiters = " ", char *token;
gets(line); token = strtok(line, delimiters);
while (token != NULL)
{
puts(token); /* Get the next word */
token = strtok(NULL, delimiters); }
}
Infosys Technologies Ltd Version no: 2.0

## The strtok Function

The strtok function is used to find the next token in a string. The token is specified by a list of
possible delimiters.

ER/CORP/CRS/LA06/003 37
Example: Palindrome
• Check whether the user entered string is a palindrome or not

Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 38
Solution
#include <stdio.h>
int iCheck_Palindrome(char acString[], int iStringLen);
int iStr_Len(char [ ]);
int main ( )
{
char acString[100]; int iStrLen, iIndex, int iPalindrome;
printf("Enter the string");
gets(acString);
iStrLen=iStr_Len(acString);
iPalindrome=iCheck_Palindrome(acString, iStrLen);
if (iPalindrome == 1)
printf("a palindrome");
else
printf("not a palindrome");
}

Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 39
Solution –(contd…)
int iCheck_Palindrome(char acString[ ], int iStrLen)
{
int iPalindrome;
int iIndex;
iPalindrome = 1;

## for(iIndex=0; iIndex<iStrLen/2; iIndex++)

if (acString[iIndex] != acString[iStrLen - iIndex - 1])
iPalindrome = 0;

return(iPalindrome);
}

Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 40
Example
• Reverse the user entered string and then print

#include <stdio.h>
void vReverse_String(char[ ]);
int iStr_Len(char [ ]);
int main( )
{
char acString[100];
char acReverseString[100];
int iStrLen;

## printf("Enter the string");

gets(acString);
iStrLen=iStr_Len(acString);
vReverse_String(acString,iStrLen);
printf(“The reversed string is %s \n”, acString);
}
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 41
Solution
#include <stdio.h>
void vReverse_String(char[ ]);
int iStr_Len(char [ ]);
int main( )
{
char acString[100];
char acReverseString[100];
int iStrLen;

## printf("Enter the string");

gets(acString);
iStrLen=iStr_Len(acString);
vReverse_String(acString,iStrLen);
printf(“The reversed string is %s \n”, acString);
}

Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 42
Solution –(contd…)
void vReverse_String(char acString[ ], int iStrLen)
{
int iIndex;
char cTemp;
for(iIndex = 0; iIndex < iStrLen/2; iIndex++)
{
cTemp = acString[iIndex];
acString[iIndex] = sString[iStrLen - iIndex - 1];
sString[iStrLen - iIndex -1] = cTemp
}
}

Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRS/LA06/003 43
Multidimensional arrays
Declaration

## int a2[3][2]; -/* a2 is an array of 3 elements, each of which is an array of 2 int

reserves memory for 3*2 ~ 6 element / integer values *
float temperatures[12][31]; /* Used to store temperature data for a year */

## float altitude[100][100]; /* Used to store the altitudes of 10000 grid points

of a 100 by 100 mile square */

Memory Allocation

## a2 a2[0][0] a2[0][1] a2[0][2] a2[1][0] a2[1][1] a2[2][2]

Accessing elements
int i, j; for(i = 0; i < 5; i++) { for(j = 0; j < 7; j++) a2[i][j] = 0; }

Infosys Technologies Ltd Version no: 2.0

C does not have true multidimensional arrays. However, because of the generality of C's type system, you
can have arrays of arrays, which are almost as good. (This should not surprise you; you can have arrays of
anything, so why not arrays of arrays?)

Just as we declared a two-dimensional array using two pairs of brackets, we access its individual elements
using two pairs of brackets:
Make sure that you remember to put each subscript in its own, correct pair of brackets.
Neither int a2[5, 7]; /* XXX WRONG */
nor a2[i, j] = 0; /* XXX WRONG */
nor a2[j][i] = 0; /* XXX WRONG */
would do anything remotely like what you wanted.

While declaring arrays, there are times when you don't know the size, so you'd want to use an unsized array.
However, you must specify every dimension size except the left one. Like this:
int array2D[][5];

ER/CORP/CRS/LA06/003 44
Multidimensional arrays-(Contd…)
• Please refer to Notes page for more explanation on previous slide

Infosys Technologies Ltd Version no: 2.0

Consider an example:-
#include <stdio.h>
void main()
{
int first[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
int second[3][4] = {0, 1, 2,
3, 4, 5,
6, 7, 8,
9,10,11}; /* a clearer definition than the first */
int third[][5] = {0,1,2,3,4}; /* third[] only has one index of 1 */
int fourth[][6] = {0,1,2,3,4,5,
6,7,8,9,10,11}; /* fourth[] has 2 indices - 0 or 1 */
int i,j; int fifth[5][4]; int sixth[2][6]; int seventh[2][3];
for(i=0 ; i<5 ; i++)
{ for(j=0 ; j<4 ; j++)
{ fifth[i][j] = i * 4 + j;
}}
for(i=0 ; i<2 ; i++)
{ printf("Enter 6 integers separated by spaces: ");
for(j=0 ; j<6 ; j++)
{ scanf("%d" , &sixth[i][j]); } printf("\n"); }
printf("You entered:\n");
for(i=0 ; i<2 ; i++)
{ for(j=0 ; j<6 ; j++)
{ printf("%d ", sixth[i][j]); } printf("\n"); }
seventh[0][0] = 0; seventh[0][1] = 1; seventh[0][2] = 2; seventh[1][0] = 3; seventh[1][1] = 4; seventh[1][2] = 5;
return 0; }

ER/CORP/CRS/LA06/003 45
Multidimensional arrays-(Contd…)
• Please refer to Notes page for more explanation on previous slide

Infosys Technologies Ltd Version no: 2.0

If you ever wanted to find out how much memory your arrays occupy (1D or multidimensional), you can use
the sizeof operator.
Example for accessing multidimesional array elements
A common way to access the elements of a multidimensional arrays is with nested for loops.

#define MAXI 50
#define MAXJ 75
int i;
int j;
float values[MAXI][MAXJ];
for (i = 0; i < MAXI; i++) {
for (j = 0; j < MAXJ; j++) {
values[i][j] = whatever;
}
}
The C language performs no error checking on array bounds. If you define an array with 50 elements and you
attempt to access element 50 (the 51st element), or any out of bounds index, the compiler issues no
warnings. It is the programmer's task alone to check that all attempts to access or write to arrays are done
only at valid array indexes. Writing or reading past the end of arrays is a common programming bug and can
be hard to isolate.

ER/CORP/CRS/LA06/003 46
Multidimensional arrays-(Contd…)
• Please refer to Notes page for more explanation on previous slide

Infosys Technologies Ltd Version no: 2.0

What will happen if a program accesses past the end of an array? Suppose a program has the following code.

int val;

int buffer[10];

val = buffer[10];
/* Bug, remember that the indexes of buffer run from 0 to 9. */

What value will be in val? Whatever happens to be in memory at the location right after the end of the array. This value
could be anything. Worse yet, the program may continue to run with the incorrect value and no warnings are issued.

What will happen if a program writes past the end of an array? Suppose a program has the following code.

int buffer[10];

buffer[593] = 99;

The value of 99 will be written at the memory location, buffer + 593. "buffer" is a pointer to the beginning of the array.
buffer + 593 is pointer arithmetic for the address equal to the starting address of the array plus the size of 593 integers.
The overwriting of the value at this memory location will change the value of whatever variable is stored there. Some
other variable may have its value changed unintentionally. If the program writes unintentionally to memory locations that
not valid, the program may crash.

ER/CORP/CRS/LA06/003 47
Multidimensional arrays-(Contd…)
• Please refer to Notes page for more explanation on previous slide

Infosys Technologies Ltd Version no: 2.0

The most common cause of writing/reading to invalid array indexes are errors in loop limits.

int i;
float b[10];

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

b[i] = 3.14 * i * i;
}

## This loop should use "<" rather than "<="

The most straightforward way of passing a multidimensional array to a function is to declare it in exactly the
same way in the function as it was declared in the caller.
If we were to call func(a2); then we might declare func(int a[5][7]) { ... } and it's clear that the array type which
the caller passes is the same as the type which the function func accepts.

ER/CORP/CRS/LA06/003 48
Multidimensional arrays-(Contd…)
• Please refer to Notes page for more explanation on previous slide

Infosys Technologies Ltd Version no: 2.0

While passing single dimensional arrays as parameters to functions, the formal parameters to the function
definition were only the array name[].
Size was omitted because it was decided by the parent function which calls this function.
But when we look at passing 2-dimensional arrays as parameters to the function the formal parameters to the
function definition needs to be array name[][<size>}. We can only omit the row dimension and need to specify
the column dimension.
With multidimensional arrays being passed as parameters to functions , we need to specify all but the first
dimension of the array.

ER/CORP/CRS/LA06/003 49
Multidimensional arrays-(Contd…)
• Please refer to Notes page for more explanation on previous slide

Infosys Technologies Ltd Version no: 2.0

Another important point to understand here is what is common between arrays and pointers.
When we pass arrays as arguments to functions what is actually been passed is the starting address to the
array (ie the address of the first element of the array)

ER/CORP/CRS/LA06/003 50
Multidimensional Arrays and functions

## Passing Arrays as arguments to functions

Declaration func(int arr[][7])
Definition func(int arr[][7])
Invocation func(arr)

##  Write a program to accept values into a 2-dimensional array (arr)

and
display the row totals
display the column totals
 transpose the elements of the array.

Infosys Technologies Ltd Version no: 2.0

The most straightforward way of passing a multidimensional array to a function is to declare it in exactly the
same way in the function as it was declared in the caller.
If we were to call func(a2); then we might declare func(int a[5][7]) { ... } and it's clear that the array type which the
caller passes is the same as the type which the function func accepts.
Concluding , the formal parameters declaration within the function definition must include explicit size specifications in all of the subscript
positions except the first

ER/CORP/CRS/LA06/003 51
Array of strings
Declarations
char caName[5][10]; - Creates a 2D array of characters with 5 rows,
each row having 10 characters
caName[0] - 1st single dimensional character array, which can
be used to hold 10 characters or a string of 9 characters
caName points the 1st element of the array ie caName[0][0];

caName

Infosys Technologies Ltd Version no: 2.0

## An array of strings is just a two dimensional array of characters.

Consider this:
char names[7][6] = { "Ryan", "Tom", "Chad", "Jackie", "Tara", "Lori", "Kelly" };
This gives you an array of seven names. The first number in brackets says how many strings there will be, and the second number is the
amount of characters any of the strings can have.
If you left out the numbers in the brackets, the compiler would figure it out for you using the longest name length as the maximum length (the
second number in brackets). To reference a string, only use the first dimension. So the statement printf("%s", names[0]); would print the
name Ryan on the screen. Do not reference a string like this names[3][0]. That refers to the character 'J' not the string "Jackie".

ER/CORP/CRS/LA06/003 52
Example
#include <stdio.h>
#include <string.h>
void main()
{
char *mess[] = {
"Pen",
"Pencil",
"Scale",
"Sharpner",
"Scissor"
};
printf("%s",mess[0]);
printf("%c",mess[3][4]);
}
Consider the declaration above and answer the questions

• Is it a valid declaration?
• mess[0] pointer to the string “Pen”
• Character at mess[3][4] is ?
Infosys Technologies Ltd Version no: 2.0

## The declaration is valid.

Each the string is referred to using mess[0] ->Pen,mess[1]-> Pencil and so on
mess[3] -> Sharpner
Mess[3][0]->S mess[3][1]->h……..hence mess[3][4] -> p

ER/CORP/CRS/LA06/003 53
Summary
• Definition of strings
• Input/output of strings
• String functions
• Multidimensional Arrays