Sie sind auf Seite 1von 55

£

M ARRAYS
5.1.1. Introduction
> For storing a single data item programmers uses variables; but in many
application, programmers need to store a large amount of data, thus for storing
large amount of data we need to declare large number of variable which is not
convenient. And these variables are independent and not related with each other,
so for storing large amount of data C provides the concepts of Array.

> Array means collection. An array is used to store elements of the same type. It is
a very popular and useful data structure and stores data elements in contiguous
locations. More than one element is arranged in sequence so it is also called a
composite data structure.

> Array is a linear and homogenous data structure. Homogenous means that the
same types of elements are stored in it.
or
An array is a homogenous, fixed-size sequenced collection of elements of the
same data type which are allocated contiguously in the memory.

> Following figure shows the concept of array where the lowest address
corresponding to the first element and the highest address to the last element.
First Element Last Element
1 ___________________________________!
Numbers[0] Numbers[l] Numbers[2] Numbers[3]

Benefits of Arrays
1) They are used to represent all sorts of lists.
2) They are used to implement other data structures such as stacks, queues, heaps,
etc.

Limitations of Arrays
1) The prior knowledge of number of elements in the linear array is necessary.
2) These are static structures. Static in the sense that, whether memory is allocated
at compilation time or runtime, their memory used by them cannot be reduced or
extended. Since the elements of these arrays are stored in consecutive locations,
the insertions and deletions in these arrays are time consuming. This is because
of moving down or up to creates a space of new element or to occupy the space
vacated by the deleted element becomes complex in array of large elements size.
5.1.2. Characteristics of Arrays
1) Array elements are stored in successive memory locations.
2) Once array is declared, its lowest bound cannot be changed, but the upper bound
can be expanded with the compiler. The array name itself is a constant pointer
and user cannot modify it. Therefore, the lowest bound of an array cannot be
expanded.
3) Array name itself is a pointer.
4) All the elements of an array share the same name, and they are different from
one-another with the help of the element number.
5) Amount of memory required for an array depends upon the data type and the
number of elements.
Total bytes = size of (data type)* size of array
6) Once an array is created, we cannot remove or insert memory locations. An
element can be deleted or replaced but the memory location remains as it is.
7) Once an array is declared and not initialized, it contains garbage values.
8) If we declared an array as a static (predefined keyword) then all the elements are
initialized to zero.

5.1.3. Array Terminology


1) Size: Number of elements or the array’s capacity to store elements denotes the
size, which is always mentioned in the square bracket ([]).
2) Type: It refers to data type. It decides which type of element is stored in the
array. It also instructs the compiler to reserve memory according to data type. It
can be int, float, double, char etc.
3) Base: The address of the first element (0th) element is a base address.
4) Index: The array name is used to refer to the array element. For example, as
shown in figure Num[x] is the array name and x is the index. The value of x
begins from 0 onwards depending on the size of the array. The index value is
always an integer value.
5) Range: The index of an array, i.e., the value of x varies from the lower bound to
the upper bound while writing or reading elements from an array. For example,
for num[100] the range of the index is 0 to 99.
6) Word: This indicates the space required for an element. In each memory
location, a computer can store a data piece. The space occupied varies from
machine to machine. If the size of the element is more than memory location
provided then it occupies two successive memory locations. The various data
types such as integer, float, long, etc., needs more than one byte in memory.
5.2. ONE-DIMENSIONAL ARRAY
5.2.1. Definition
A list of items can be given a common name and the individual items can be
referenced using only one subscript. Such variable are referred to a singlesubscript
variable or a one-dimensional array.

The linear arrays are also called one-dimensional arrays, since each element in the
array is referenced by a single subscript. The one dimensional array is the array in
which the elements are represented in single row (figure 5.1).

arr[0] arr[l] arr[2] arr[3] arr[4] arr[5] arr[6] arr[7] arr[8] | arr[9]
I 4 I I I. I I II I
50 70 93 83 33 44 77 88 99

t
1
o
U)

Name
of
the
arra
Array index
Values (of memory
y
location) Figure 5.1
5.2.2. Declaration & Initialization of One Dimensional
Array
Consider the following code that initializes while declaring array
i) int codes[10] = {1, 2, 3,4, 5, 6, 7, 8, 9, 10};
ii) int codes[10] = {1,2};
iii) int codes[10];

Explanation
> In the first statement, codes array is an ‘integer array of ten elements’, which has
10 elements initialized with values ranging from 1 to 10.
> In the second statement, the first two of the codes array are set to 1 and 2, and the
rest 8 values are left blank. The last statement does not initialize anything. If you
do not initialize the array then it will be full of junk/garbage items.
> In the third statement, all the values of the codes array are initialized to 0.

Program 1: To declare an array of characters.


#include<stdio.h>
#include<conio.h>
void main()
{ . charname[4]; /* declare an array of characters */ name[0]='D'; name[l]='a';
name[2]='v';
name[3]='e'; ,
clrscr();
printf ("The name is %s\n",name); printf ("Third
letter of name is: %c \n",name[2]); //printf ("Part of
the name is %s\n", name[l]); getch();
}
Output

Explanation: The first thing new is the line that defined a “char” type of data entity.
The square brackets define an array subscript in C, §nd in the case of the data
definition statement, the 4 in the brackets defines 4 data fields of type “char” all
defined as the variable “name”.
In the C language, all subscripts start at 0 and increase by 1 each step up to the
maximum which in this case is 3. We, therefore, have 4 “char” type variables named,
“name[0]”, “name[l]”, “name[2]”, and “name[3]”. In C, the subscripts actually go
from 0 to one less than the number defined in the definition statement.

Initialization Using a Loop


A loop can be used to initialize when the array declared is very long or when the array
elements have a logic associated with the array index.
For example, suppose we want to plot the ramp function which is given by f(x) = x. In
this case, we will use a loop to initialize the array. The code snippet shows how to
initialize an array for the ramp function.

int myRamp[100];
int i;
for(i = 0; i < 100; i++)
{
myRamp[i] = i; //This is same as f(x) = x
}
Program 2: To initialize an array.
#include<stdio.h>
#include<conio.h>
main()
{
int i[4]={l,2,3,4}, j;
clrscr();
printf("The elements in array after initialization");
for(j=0; j<=4; j++)
{
i[j] =j;
printf("\n i[%d] = %d",j, i[j]);
}
getch();
}
Output
PI DOSBor 074, Cpu speed: «ax 100t cycles Raneskip 0 rn.p
r
flfiaents in arrau p initial iwt inn
a-' 0
HI] - 1 ’ r 2 ] - 2 'jp•;"

523 . Accessing and Displaying Array Elements


> C language uses single index to access individual elements in a onedimensional
array.

For example, given the marks in an array the first element is accessed as:

marks [0]
To process all the elements^ in marks, a loop similar to the following code is used:

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


{
process (marks [i]);
}
Where, i is an integer variable.
> The data represented in an array is actually stored in the contiguous memory cells
of the machine. Because computer memory is linear, a one-dimensional array can
be mapped on to the memory cells in a rather straight forward manner. Storage for
element marks[i + 1] will be adjacent to storage for element marks [i] for i = 1,
2,.... 10. To find the actual address of an element one simply needs to subtract one
from the position of the desired entry and then add the result to the address of the
first cell in the sequence.
> The array’s name is a symbolic reference for the address to the first byte of the
block of memory allocated for the array. The address of the first byte for the array
is also known as base address of the array.
> Whenever we use the array’s naiftie, we actually refer to the first byte of the array.
The index represents an offset from the beginning of the array to the element
being referenced. With these two facts of information, the C compiler can
calculate the address of any element in the array using the following simple
formula:

element address = base address + (size of (element) * index)


or
address (marks[i]) = base address + (size of (element) * i)

For example, consider an array of marks of 10 elements. The address of marks[4],


If the first cell in the sequence marks[l], marks[2], .... marks[10], was at address
16, then A[4] would be located at 16 + (4 - 1) = 19, as shown in figure. We
assume that the size of each element stored is one unit.
16 17 18 ___________ ________ 25
Memory Cells
marks[l] marks[2] marks[3] ....................................... marks[10]

> Here is the section of code that places data into an array to displaying output: for

(i=0; i<=29; i++)


{
printf ("\nEnter marks");
scanf ("%d", &marks[i]);
}

The for loop causes the process of asking for and receiving a student’s marks from
the user to be repeated 30 times. The first time through the loop, i has a value 0, so
the scanf() statement will cause the value typed to be stored in the array element
marks[0], the first element of the array.

This process will be repeated until i becomes 29. This is last time through the
loop, because there is no array element like marks[30].

In the scanf() statement, we have used the “address of’ operator (&) on the
element marks[i] of the array. In so doing, we are passing the address of this
particular array element to the scanf() function, rather than its value; which is
what scanf() requires.

Program 3: To add the element in an array.

#include<stdio.h>
#include<conio.h> '
void main()
{
int i[4]; int j; int Addition=0;
clrscr();
printf("enter the values for addition & press enter key after entering each value:
");

for(j=0; j<=4; j++)


{.
scanf("%d", &i[j]);
}
for(j=0; j<=4; j++)
{
Addition = Addition+i[j];
}
printf("\n Addition of all values = %d", Addition); getch();
}

5.2.4. Working with One-Dimensional Array


There are primarily six basic operations that can be performed on an array.
1) Traversal: Accessing each and every element of an array.
2) Search: Finding the subscript of a given value in the array, if it exists.
3) Insertion: Adding a new element into the array.
4) Deletion: Removing an existing element from the array.
5) Sorting Arrays: Sorting is used to arrange element in increasing or decreasing
order.

5.2.4.I. Array Traversal


It can be done both sequential and random manner. This is because of the linear
storage of arrays in memory. The only constraint here is that the subscript of the
array should be within bounds of the array size.
For example, a[10] when the size of the array is 5, can lead to undefined behavior of
the program. The array subscripts should be between 0 and the (size of array - 1).
5.2.4.2. Searching in an Array
The process of finding out the presence of a given key in an array is called searching.
The search is successful if the key is found and the location of the key is returned
back.There are lots of searching techniques available and some frequently-used
searches in algorithm are:
1) Linear Search/Sequential Search: In linear search, we access each element of an
array one by one sequentially and see whether it is desired element or not. A search
will be unsuccessful if all the elements are accessed and the desired element is not
found and successful if desired element is found-.

Program 4: Program to search an element using sequential search.


#include <stdio.h>
#include <conio.h> void main ()
{
int array[10], n,i,item,flag=-l; clrscr();
printf("Enter the array element ="); for(i=
0;i<10;i++)
{
scanf("%d",&array[i]);
}
printf("\n Enter the searching element' =");
' scanf("%d",&item);

for(i=0;i<10;i++)
{
if(item==array[i])
{
flag=i;
break;
}

}
if(flag>=0)
printf("\n %d is found at the position %d", item, flag+1);
else
printf("\n item does not found");
getch();

}
Output

2) Binary Search: Another relatively simple method of accessing an array is the


binary search method. The entries in the array are stored in alphabetically or
numerically increasing order.
Binary search requires sorted data to operate on. In this method, search begins by
examining the records in the middle of file rather than the one of the ends as in
sequential search.
Program 5: To search an element using binary search.
/*Binary search [int array]*/
#include <stdio.h>
#define TRUE 0
#define FALSE 1
int main(void)
{
int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int
left = 0; int right = 10; int middle = 0;
int number = 0; ■
int bsearch = FALSE; int i = 0;
clrscrQ;
printff ARRAY: "): for(i
= 1; i <= 10; i++)
printf("[%d] ”, i);
printf("\nSearch for Number: "); scanf("%d",
&number);
while(bsearch == FALSE && left <= right)
{
middle = (left + right) / 2;
if(number == arrayfmiddle]) {
bsearch = TRUE;
printf("** Number Found **\n");
}
else
{
if(number < array [middle]) right = middle - 1;
if(number > array[middle]) left = middle + 1;
}
}
if(bsearch = = FALSE)
printf("~ Number Not found —\n"); getch();
}
Output

5.2.4.3. Insertion into an Array


An array grows as elements are inserted into it. The insertion process should take care
that the allocated size of array is maintained. When the number of elements in an array
is equal to the initial declaration, we should not insert any more elements into the
array. This may lead to runtime errors.

Elements could be added either at the end of the array or at any user defined position.
Adding the element at the end of the existing array is very simple’Bin to insert an
element at a user defined position calls for little more efforts. From the position to the
end; the element has to be pushed-down while adding an element at the end of array.
The following program shows insertion into an array.

Program 6: To illustrate Insertion into an Array.


#include<stdio.h>
int array[15] = {0}; // array is initialized to zeros,
int arraypos = 0;

void insert_at_end(int element)


{
if(arraypos <= 14)
{
array[arraypos] =
element; arraypos+=1;
}
else
printf("Array full !!!");
}
void insert_at (int element, int position)
{
int i;
if(arraypos <= position)
. printf("Position invalid !!!");
// array size is not as big as the position.
else
{
if (arraypos <= 14)
{
for(i = arraypos+1; i>position; i—)
array [i]=array[i-l]; array [position] =
element; arraypos += 1;
}
else
printf("Array full!!!");
}
}
void main(void)
{ .. int i, element, position;
clrscr();
for(i = 0; i < 5; i++)
< • „ printf("enter element to
insert:"); scanf("%d", &element);
insert_at_end (element);

printf("enter position to insert at: ");


scanf("%d", &position); printf("enter
the element to insert: "); scanf("%d",
&element); insert_at(element,
position);
for(i = 0; i < 10; i++)
printf("%d\n", array [i]);
Output
m DOSBox 0 74. Cpu speed: ms 100% cydes. Fraraeskip 0, Prolan

inter eSement to insert: i ' -----
:nrter element to insert: 2
inter element to insert: 3
;ntcr elempnt to insert: 4 .
niter el ement to insert: 5 .
inter position to insert at: 3
:nter the element to insert: 5

}
5.2.4.4. Deletion from an Arrav
Because an array is a contiguous storage of element, the deletion of an element has
to be dene with a bit of caution. When an element in an array is deleted (provided, it
is not being the last element) it is required to be rearranged so that no holes are
present in it and array size has to be marked accordingly.
Program 7: To illustrate the deletion from an Array.
#include<stdio.h> ’
int array[15] = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int
array_size = 10; //'array is initialized to 0.
void remove_at (int position)
{
int i;
for(i = position; i < array_size-l; i++)
array[i] - array[i + 1]; // deletes the element at that position .
array[array_size-lj = 0;
array _ size = array_size-1; //reduces the array size by 1 void

delete_first (int element)


{
int i;
for(i = 0; i < array_size; i++) if (array [i] == element)
{
remove_at (i); //deletes the first occurrence of the element i =
array_size;

void delete_all(int
element) {
int i;
for(i = 0; i < array_size;
i++) if (array[i]==element)
remove_at(i); //deletes every occurrence of the element
}
void main(void)
{
int element, i; clrscr();
printfO'Enter the element to delete (only first occurrence): ); scanf("%d",
&element); .
delete_first(element); ^
printf("Enter the element to delete (all occurrence):"); scanf("%d", &element);
delete_all(element);
for(i = 0; i < 15; i++)
printf("%d\n", array [i]);
5.2.4.5. Sorting Arrays
> Sorting is the process of arranging the elements in some logical order. I his
logical order may be ascending or descending in case of numeric values or
dictionary order in case of alphanumeric values.
> There can be three classes of algorithms according to the memory
requirements.
i) Sort in place and use no extra memory except perhaps for a small stack or
table.
ii) Algorithm that use a Jinked-list representation and so use N extra words
of memory for list pointers.
iii) Algorithms that need enough extra memory space to hold another copy of the
array to be sorted.
Algorithm: Bubble Sort
Sorts an Array A with N elements.
BUBBLE_SORT (A, N)
Step 1: Initialization Set I =0
Step 2: Repeat step 3 to 5 Until I < N
Step 3: Set J = 0
Step 4: Repeat Step 5 until J < N - i -1 Step 5: If A[J] > A[J+1] then Set temp =A[J]
Set A[J]
Set A[J] = A[J+1]
Set A[J+l]=Temp End If
Step 6: Exit
The algorithm is straightforward. Before each pass, the interchange marker is
initialized to zero. This marker is incremented each time an interchange is made. If at
the end of a pass, marker has a value of zero, the sort is complete.
Program 8: To illustrate the bubble sort.
#include<stdio
,h> void main()
{
int A[20], N, Temp, i, j; clrscr();
printf(“\n\n\t ENTER THE NUMBER OF TERMS
scanf(“%d”,&N);
printf(“\n\t ENTER THE ELEMENTS OF THE ARRAY.
for(i=0; i<N; i++)
{ . gotoxy(25, 11+i);
scanf(“\n\t\t%d”,
&A[i]);
}
for(i=0; i<N-l; i++) for(j=0; j<N-i;j++) if(A[j]>A[j+l])
'{
Temp = A[j];
A[j] = A[j+1];
A[j+1] = Temp;
}
printf(“\n\tTHE ASCENDING ORDER LIST IS... An”);
for(i=0; i<N; i++)
printf(“\n\t\t\t%d”,A[i]);
getchO;
for(i=0;i<=9;i++)
printf(" %d\t" ,arr[i]);
getch();
}
void quicksort(int a[],int lower,int upper)
{
int i;
if(upper>lower)
{
i=split(a,lower,upper);
quicksort(a,lower,i-1);
quicksort(a,i+1,upper)
;
}
}
int splk(int a[],int lower,int upper)
{
int i,p,q,t; p=lower+l; q=upper; i=a[lower];
while(q>=p)
{
while(a[p]<i) ,
p++;
while(a[q]>i
)
q--;
if(q>p)
{
t=a[p]; a[p]=a[q]; a[q]=t;
}
}
t=a[lower]; a[lower]=a[q]; a[q]=t; return
q;
}
Output
ujmyuimwww
5.3. ARRAYS AND FUNCTIONS
5.3.1. Introduction
A function is a self-contained program segment that carries out some specific, well-
defined task. Every C program consists of one or more functions. One of these
functions must be called main. Execution of the program will always begin by
carrying out the instructions in main. Additional functions will be subordinate to
main, and perhaps to one another.
In C, one cannot pass entire array as an argument to a function. One can, however,
pass a pointer to an .array by specifying the array’s name without index. For
example, the following program fragment passes the address of I to funcl():
int main()
{ . int i[10]; funcl(i);
}
If a function receives a pointer to a single- dimension array, you can declare its formal
parameter in one of three ways: as a pointer, as a sized array, or as an unsized array.
For example, to receive i, a function called funcl() can be declared as
void fund (int *x)
{

}
Or
void fund (int x[10])
{

}
Or
void fund (int x[])
{

}
All three declaration methods produce similar result because each tells the compiler
that an integer pointer is going to be received.
Types of Array Passing
The array elements can be passed to a function in two ways:
1) Call by value,
2) Call by reference.
5.3.2. Passing Array Using Call by Value
In the call by value method, one passes values of array elements to the function.
Program 10: Passing of an array element of one dimension to a function using
call by value mechanism.
#include<stdio.h>
#define SIZE 10
int isEven(int k);
void main()
{
int arr[SIZE]={ 12,15,20,17,25,50,11,10,38,13}; int i; clrscr()‘
printf("\t ******* CHECKING FOR EVEN OR ODD NUMBER BY
. USING CALL BY VALUE *******\n"); for(i=0;i<SIZE;i++)
{ ' if(isEven(arr[i]))
{
printffNUMBER %d IS EVEN",arr[i]);
}
else
{
printf("NUMBER %d IS ODD",arr[i]);
}
printf("\n");
}
getch();}
/*function to check whether the argument is even number*/
-1. int isEveu(int k) ' :: .*•" • ' ■ ' ■ .** ' '
• ■> ' ■
if(k%2==0) return k; else
return 0;}

In passing an array as a parameter to a function it is passed as a reference parameter.


What is actually passed is the address of its first element.

Since arrays are passed by reference this means that if the function changes the value
of an element in an array that is a parameter of the function then the corresponding
actual array of the call will have that element changed.

Program 11: Demonstrate the passing of an array element of one dimensional to


a function using call by reference mechanism.
#include<stdio.h>
#define SIZE 10
void modify(float *); /*function prototype*/
5.3.3. Passing Arrays Using Call by Reference
In the call by reference, one passes address of array elements to the function.

void main()

{
float arr[SIZE]={ 12,15,20,17,25,50,11,10,8,13};
int i;
clrscrQ;

printf("\t ******* MODIFICATION BY CALL BY REFRENCE printf("\n

ELEMENTS OF ARRAY BEFORE MODIFICATION \n\n");


for(i=0;i<SIZE;i++) printf(" %.2f’,arr[i]);

for(i=0;i<SIZE;i++)
modify(&arr[i]);
printf("\n\n\n ELEMENTS OF ARRAY AFTER MODIFICATION
\n\n");
for(i=0;i<SIZE;i++) printf(" %.2f',arr[i]); printf("\n");
getch(); .
}

/^function that increases the value of its argument by 10%*/


void modify(float *p)

{
*p+=*p*.l;
Output

Program 121 To print the sum of Five numbers through function.

#include<stdio.h>
void main()
{
}
int num[5],i;
void add(int[]);
clrscr();
printf("\t ******** SUM USING CALL BY REFRENCE
printf(" ELEMENTS OF ARRAY ARE:\n"); for(i=0;i<5;i++)

{
printf( ' NUMBER %d IS : ",i + 1);
scanf(" %d", &num[i]);
}
add(num);
getch();
}
void add(int *num)

{
int sum=0,i;
printf("\nll— ....... .........- ........... - ------------- --------------------------------- ll\n\n");
for(i=0;i<5;i++)
sum += num[i];
printf(" SUM OF 5 NUMBERS = %d \n",sum);

}
Output
k ■ fX)fjfk>x 0.74, C.pu speed: max 100% cycles. Frairaeskip 0. Program:
~~ «««««* SUM USING CALL BY REFBEMCE ******.

ELEMENTS OF MAY ARE


NUMBEH 1 IS : 3
HUMBER 2 IS : ?.
NUMBER 3 IS : 3
NUMBER 4 IS : 5
NUMBEB 5 IS : 6

SUM OF 5 NUMBERS = 25

5.4. TWO DIMENSIONAL ARRAYS


5.4.1. Definition
> Array are used to store the data item in the form of a list by using the one-
dimensional array, but some time we have to store the data in the tabular form, then
for storing data in the tabular form C provides the concept of twodimensional
array. The two-dimensional array is also known as a matrix.
> A two-dimensional array is a grid having rows and columns in which each element
is specified by two subscripts. It is the simplest of multi-dimensional arrays.
For example, an array a[m][n] is an m by n table having m rows and n columns
containing mxn elements. The size of the array (total number of elements) is
obtained by calculating mxn.

0!2

a[j][k] 0 <= j <= m - 1 0 <=


k <= n - 1

< --------------------- n columns ------------------------- >.

n-2n-1

Here a[j][k] denotes the element in the jth row and kth column.
> Two-dimensional arrays are called matrices in mathematics and tables in
business applications; hence two-dimensional arrays are sometimes called
matrix arrays.
> A two-dimensional array differentiates between the logical and physical view of
data. A 2-D array is a logical data structure that is useful in programming and
problem-solving. For example, such an array is useful in describing an object
that is physically two-dimensional such as a map or checkerboard.

5.4.2. Declaration of Two-Dimensional Arrays


Two dimensional arrays are declared by the use of well-defined syntax as given
below.

Syntax
type variable_name[number of rows][number of columns];

For example,
int a[5][5];

Here ‘a’ is the name of the array of type int of size 5 by 5. The array elements are
a[0][0], a[0][l] ......... .. a[4][4],

5.4.3. Initialization of a Two-Dimensional Array


The general syntax of initialization of the two-dimensional array is given below.

Syntax
type array_name[row_size][column_size] = {array_elementl,
array_element2................ array_element_n}
For example, consider the following matrix which shows the case where A has 3
rows and 4 columns. Each row contains those elements with the same first subscript,
and each column contains those elements with the same second subscript.
Columns
1 2 3 4_
1 p A[l, 1] A[l, 2] A[l, 3] A[l, 4]
Row 2 A[2, 1] A[2,2] A[2,3] A[2,4]
3 l_A[3,l] A[3,2] A[3,3] A[3,4]
Figure 5.3: 2-Dimensional 3x4 Array A

5.4.4. Accessing and Displaying Array Elements


> The elements of a two-dimensional array can be accessed sequentially in two
ways - either as row elements or as column elements. To access the elements of
two-dimensional arrays by rows, an outer for loop is used for the row index and
an inner for loop is used for the column index.
y To access the elements of two-dimensional arrays by columns, the outer for loop
index must be the column index and the inner for loop index must be the row
index. _
Sequential Access by Rows
for each row i
for each element of the row
access element^ ,
end for end for
Sequential Access by Columns
for each column j
for each element of the column
access elementy end for end for
> All of the elements of the array can be accessed by rows as follows-
for(i=0;i<IMAX; i++) '
{
for(j=0;j<JMAX; j++)
{
—a[i]
}
}
^ All of the elements of the array can be accessed by columns as follows:
for(j=0;j<JMAX; j++)

{
for(i=0; i<IMAX; i++)
{,
—a[i] [j]...
}
}
> A single element of the array can be accessed as follows:
a [2] [3] /* refers to the element in the third row and the fourth column */
> The array arrangement shown in figure 5.4 is only conceptually true. This is
because memory does not contain rows and columns. In memory whether it is a
one-dimensional or a two-dimensional array, the array elements are stored in one
continuous chain. The arrangement of array elements of a twodimensional array
in memory is shown below:
s[0][0] s[0][l] s[l][0] s[l][l] s[2][0 s[2][l] s[3][0] s[3][l]
]
1234 56 1212 33 1434 80 1312 78 |

5002 5004 5006 5008 5010 5012 . 5014 5016

Figure 5.4
Here, s denotes student array with the marks of students.
One can easily refer to the marks obtained by the third student using the subscript
notation as shown below:
printf ("Marks of third student = %d", stud[2][l]);

5.4.5. Memory Representation of Two-Dimensional


Arrays
Let A be a two-dimensional mxn array and pictured as a rectangular array of elements
with m rows and n columns, the array will be represented in memory by a block of
mxn sequential memory locations.
The two-dimensional array is also called a matrix.
Mathematically, a matrix A is a collection of elements ‘ay’ for all i and j’s such that 0
< i < m and 0 < j < n. A matrix is said to be of order mxn. A matrix can be
conveniently represented by a two-dimensional array.
The various operations that can be performed on a matrix are - addition,
multiplication, transposition, and finding the determinant of the matrix.
An example of 2-D array can be arr[2][3] containing 2 rows and 3 columns and
arr[0][l] is an element placed at 0th row and 1st column in the array.
A two-dimensional array can thus be
represented as given in figure 5.5.
Column 0 Column 1 Column 2
Row 0
Row 1 \
arr[0][l]
S3 k

Figure 5.5: Representation of 2-D Array in


Memory

5.4.6. Row Major and Column Major Order


All elements of a matrix get stored in the memory in a arr[0][0]
' • base(arr)
linear fashion. The two ways in which elements can
be represented in computer’s memory are — arr[0][l]
Row 0 *
‘row major order’ and ‘column major order’.
arr[0][2]
In row major representation the first row of the array
occupies the first set of memory locations, second arr[l][0]
occupies the next set, and so on.
< arr[l][l]
The diagrammatic representation of two- Row 1<
dimensional array arr[2][3] in row major order is arr[l][2]
given in figure 5.6.
Figure 5.6: Representation of 2-D Array in
Row Major Order
In figure 5.6, the memory locations are first occupied by the first row of the array.
Now base(arr) has the address of first element of the army arr[0][0]. We also assume
the size of each element in the array with esize.
Now let us calculate the address of an element in the following 2-D array: int
matrix[3][4] = ({1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12});
Formula to calculate the (j, k)th element of a 2-D array of m x n dimension is
A(j, k) = base(A) + W[N(j - 1) + (k - 1)]
where, W = word size, N = number of columns
Let us assume that the base address of the array matrix is 100. Since W=2 (as array is
of integer type whose size is 2), therefore, according to the formula, address of (2,3)*
element in the array matrix will be:
LOC (2, 3) = 100 + 2[4(2 - 1) + (3 - 1)]
= 100+ (4 + 2) x 2= 100+ 12= 112
Note: Lower bound of the array is assumed to be 1.
Thus we see that in the above matrix, address of (2, 3)* element which is 7 is 112 (as
depicted in the figure 5.7):
► Address

• Index

Row 1 Row 2 Row 3


r
0 1 2 3 4 5 6 7 8 9 10 11
1
i 2 3 4 5 "~n
6120 7 8 9 10 11 12
122 II
10 10 10 10 10 11 11 11 11 118 120 122
0 2 4 6 8 0 2 4 6

1(1.1) 2(1,2) 3(1,3) 4(1,4) 5(2,1)

6(2,2) 7(2,3) 8(2,4)


9(3,1) 10(3,2) 11(3,3) 12(3,4)
Matrix
Representation
Figure 5.7: Row Major
Representation
• Data

Similarly, for the column major order representation, let us consider the same matrix.
, -- ►Address

f ( f f
1(1.1) 2(1,2) 3(1,3) 4(1,4) 5(2,1) 6(2,2) 0 1 2 3 4 5 6 7 8 9 10 11
7(2,3) 8(2,4) 9(3.1) 10(3,2) 11(3,3) 1 5 9 2 6 10 3 7 11 4 8 12
12(3,4) Matrix
100 10 10 10 10 110 112 11 116 11 120 122
Representation 2 4 6 8 4 8
Data r>-
Index

Column 1 Column 2 Column 3 Column 4


To find the address of (j, k)th element in an array of m x n dimension and W word size
of each element, the following formula can be used:
A(j, k) = Base(A) + W[M(k - 1) + (j - 1)]
••• LOC(2, 3) = 100 + 2[3(3 - 1) + (2 - 1)]
Figure 5.8: Column Major
Representation
= 100 + 2(7) = 114 '
We see that the address of the same element ((2, 3)*, i.e., 7) has changed to 114
instead of 112, in column major order representation of the array. This is due to the
fact that the elements in the column major order representation are stored in a
different order, i.e., all the elements of column 1 are stored first and then all the
elements of column 2 are stored, followed by all the elements in column 3, and so
on.

Program 13: /*Illustrating accessing of two dimensional numeric arrays.*/


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

int main ()
/* an array with 5 rows and 2 columns */ int
a[5][2] = {{0,0}, {1,2}, {2,4}, {3,6},{4,8}}, inti,
j;

/* output each array element's value */ for(i=0;


i<5; i++)

{ ' for(j=0; j<2; j++) printf("a[%d][%d] = %d\n", i, j,

a[i][j]);
}
}
getch();
}
Output _____ ________________________________ — ----- --- s
----- ------ V/
i C:\ll se rsvpra veshVDes ktop\t\bitwi se.exe
[0][0] = 0 -
[0][13 0 *
[1310] - 3
[11C13 = 2
[2 3[03 - 2
[23113 = 4
[3 3[03 - 3
133 Cl =
1
343[03 4
<>
= 8

Program 14: To display two-dimensional array elements together with their


addresses.
# include<stdio.h>
# include<conio.h>
void main()
{
inti, j;
int a[3][3] = {{1,2,3}, {4,5,6}, {7,8,9}}; clrscr();
printf("Array Elements and address.\n\n");
printf(" Col-0 Col-1 Col-2\n"); ’
printf("===== ===== === \n");
printf("rowO"); for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf(" %d [%5d]", a[i][j], &a[i]U]);
printf( "\nRow%d ,i+1);
}
printf("\n "); getch();
}

Explanation: In the above program two-dimensional array is declared and


initialized. Using two nested for loops; elements of an array together with their
addresses are displayed. It is shown at the output that elements to twodimensional
array are displayed in rectangular form. But, in memory they are not
stored in this particular format. They are stored in a continuous memory location as
shown below: • J

Row, Col. A[0][0] A[0][1] A[0][2] A[1][0] A[l][ll A[l][2] uciueni [S Ar2ir2i
A[2][0] A[2][l]
9
Value 1 2 3 4 5 6 7 8
Address 4052 * 4054 4056 4058 4060 4062 4064 4066 4058

iOilVIENSIONAL ARRAYS
C also provides the concept of array of three or more dimensions, is called subs^pts
nS1°nal The multidimensional arraY is controlled by multiple

General multidimensional arrays are defined analogously. More specifically an n-


dimensional mi x m2 x....x mn array B is a collection of m, . m2... mn data
elements in which each element is specified by a as K,
K2, ..... K,, called subscripts, with the property that
1 <Ki<mi. 1 <K2<m2 ....... l<Kn<m„

The element of B with subscripts Kx, K2, .. ..Kn will be denoted by,
Bkl.k2.-kn or B[Ki, K2,...KN]

Hence, the general syntax for the multidimensional array is as follows:


array_name[Si][S2][S3] ......... [S„] where S, denote the size of the i dimension.

Insertion in Multi-Dimensional Array , t ...


The element insertion is generally handled by the programming constructs like
loops specifically for loop.
The elements of the array a2 can be filled by using the following piece of code: int i,
j;
for(i = 0; i < 5; i = i + 1)
{ . . for(j = 0; j < 7; j = j + 1)
a2[i][j] = 1 0 * i + j ;
This pair of nested loops sets a[l][2] to 12, a[4][l] to 41, etc. Since the first
dimension of a2 is 5, the first subscripting index variable, l, runs from 0 to
4. Similarly, the second subscript varies from 0 to 6.

a2 can be printed out with a similar pair of nested loops: for(i = 0; i < 5; i = i + 1)
{ . . for(j = 0; j < 7; j = j + 1)
printf("%d\t",
a2[i][j]); printf("\n");
\« .

(The character \t in the printf string is the tab character.)

The “row” and “column” subscripts can be explicitly print. for(j = 0; j <7; j = j + 1)
printf("\t%d:", j); printf("\n");
for(i = 0; i < 5; i = i + 1)
{
printf("%d:", i); •
for(j = 0 ; i < 7 ; j = j + 1)^' '*~
printf("\t%d", a2[i][j]);
printf("\n");

}
This fragment would print:
0: 1: 2: 3: 4: 5: 6:
0: 0 1 2 3 4 5 6
1: 10 11 12 13 14 15 16
2: 20 21 22 23 24 25 26
3: 30 31 32 33 34 35 36
4: 40 41 42 43 44 45 46

Program 15: Illustrating three-dimensional array.


# include<stdio.h>
# include<conio.h> void main()
{
int array_3d[3] [3] [3];
int a,b,c;
clrscr();
printf("\t ******** 3_j) ARRAY ********\n"). for
(a=0;a<3;a++) ’
for(b=0;b<3 ;b++)
for(c=0;c<3 ;c++)
array_3d[a] [b] [c]=a+b+c;
for(a=0;a<3;a++)
{
printf("\n");
for (b=0;b<3;b++)
{
for (c=0;c<3;c++) printf("%3d",
array_3d[a][b][c]); printf("\n");
}
}
getch();

Explanation: The three-dimensional array called array_3d in the code is initialized.


The first for loops are used for adding the values of a, b, and c. Here,
initially a and b are zero and ‘c’ varies from 0 to 2. Hence, the addition of a, b and c
will be 0 1 2. This will be printed in the first row. The second output row in which
a=0, b=l and c varies from 0 to 2. Thus, the output of second row will be 2 3. In this
way the values of a, b and c are changed and the total 27 iterations are
carried out.

Program 16: Read the quantity and rate of certain items using
multidimensional array. Calculate total cost by multiplying quantity and rate
and offer 2% discount on it and display the net amount.
# include<stdio.h>
# include<conio.h>
main ()
{
long m[2] [2] [2] [2];

printfC'Xt^******* QUANTITY & RATE USING MULTI-D ARRAY clrscr();


printf("ENTER
QUANTITY AND
RATE:- \n");
for(a=0;a<2;a++)
for(b=0;b<2;b++)
for(c=0;c<2;c++)
for(d=0;d<l ;d++)
{
if (a==0)
printf("a=%d b=%d c=%d d=%d\n",a,b,c,d); scanf("%ld
%ld",&m[a][b][c][d],&m[a][b][c][d+1]);
}
else

m[a] [b] [c] [d]=m[a-1 ] [b] [c] [d] *m[a-1 ] [b] [c] [d+1];
m[a] [b] [c] [d+1 ]=m[a-1 ] [b] [c] [d] *m[a-1 ] [b] [c] [d+1 ]*2/l 00;
}

}
printf(" ___________
||==================================:=== ---------------------------------------

printfC "QUANTITY RATE AMOUNT DISCOUNT(@2%) NET AMOUNTXn");


-
printf(" __________________ =========
========ll\n");
for(a=0;a<l ;a++)
for(b=0;b<2;b++)
for(c=0;c<2;c++)
for(d=0;d< 1 ;d++) '
{
printf("\n% 1 Old % 101d",m[a][b][c][d],m[a][b][c][d+1 ]);
Hc"[dSIt+i“bMd“ ]y21d00’ '•m[a+11[b]M'dl-nlla+1lM[c][<i+l],m[a+lJ[b
1’
printf("\n

==ll\n");
getch();

Output
DOSBox G 74. Cpu speed: max 100% cycles, rtameskip 0, Procram

Explanation
In the above example the four-dimension array m[2] [2] [2] [2] is declared. The first
four for loops are used to read the quantity and rate. The values of variables
t . tlmes remains zero where as values of ‘b’ and ‘c’ changes to 1 (0,0), 2 (0,1) 3 (1,0)
and 4 (1,1). This happens during execution of for loops. The’ if statement checks as to
whether the value of a==0 or not. As long as its value is zero reading operation is
performed. When it is greater than zero, rate and quantity are multiplied for obtaining
the amount. Also discount is calculated. Amount and discount are stored in the array
m[2] [2] [2] [2], Net amount is printed after subtracting discount from gross amount.
5,6 STRINGS
5.6.1. Definition and Concepts
> A string is a sequence of symbols that are chosen from a set of alphabet. A string
is, essentially, a sequence of characters.
> A string is generally understood as a data type storing a sequence of data values,
usually bytes, in which elements usually stand for characters according to a
character encoding, which differentiates it from the more general array data type.
> Strings in C are represented by arrays of characters. The end of the string is
marked with a special character, the null character, which is simply the character
with the value 0. For example, we can declare and define an array of characters,
and initialize it with a string constant:
char string[] = “Hello, world!”;
> String are used to suggest strings in which the stored data does not (necessarily)
represent text.
> A variable declared to have a string data type usually causes storage to be
allocated in memory that is capable of holding some predetermined number of
symbols.
> When a string appears literally in source code, it is known as a string literal and
has a representation that denotes it as such.
For example,
char unit;
unit = ‘F’ ; /* for Fahrenheit */

unit = ‘C’; /* for Centigrade */


> Most codes and ID’s require more than one character. In mailing addresses, two
characters are used to identify a state and five characters are used to identify a
zip code. They could be stored in character array as
follows:
char state[2], zip[5];
Numbers such as zip codes, which are used for identification purposes and are
not used in arithmetic, should be stored as arrays of type char, rather than
as integers.

5.6.2. Declaration of Strings


In C, a character array is declared using the basic data type char and the derived data
type array.
Syntax:
char StringName[array_size];
For example, char chararray[n];

The data type here is char, the name of the array is chararray, and n is the number of
elements.

For example, consider the following declaration and allocation of storage for a
character array that can hold 10 characters, char chararray [10];
chararray[0] = ‘a’;
chararray[l] = ‘x’;
chararray [2] = ‘c’;
chararray [3] = ‘b’;
chararray [4] = T;
chararray[5] = ‘k’;
chararray[6] = ‘m’;
chararray[7] = ‘d’;
chararray[8] = ‘g’;
chararray[9] = T;

The preceding characters are stored as follows:


a X c b 1 k m d g f

Here m above example 10 characters are stored in this array chararray. As with any
array these characters can only be accessed individually.

5.6.3. Initialization of Strings


Initialization of character data is similar to that of other types of arrays, since most
character data is stored in arrays of type char. An array can be initialized by explicit
assignment of values to its elements.
Example: An array can be initialized in the array declaration as shown in the
following:
char mystate[2] = {‘C’, ‘A’};
char myzip[5] = {‘9’, ‘2’, ‘3’, ‘1’, ‘2’}; //here ‘9’, ‘2’... are treated as characters not
integers.

Example: Initialization of a string must have the following form, (this is similar to
initializing a one-dimensional array):
charmonthlf] = { ‘J’, ‘a’, ‘n\ ‘u\ ‘a’, V, y, ‘\0’};
Then the string month is initialized to January. This is perfectly valid but C
offers a special way to initialize strings. The above string can be initialized as:
char month 1[] = “January”;
The characters of the string are enclosed within a pair of double quotes. The compiler
takes care of storing the ASCII codes of the characters of the string m memory and
also stores the null terminator in the end.
It is a one-dimensional array. Each character occupies a byte. A null character C\0’)
that has the ASCII value 0 terminates the string. Figure 5.9 shows the storage of the
string January in the memory. Recall that \0 specifies a single character whose ASCII
value is zero.

Character string .
terminated by a ^ null
character “\0”

\0
Figure 5.9: String Stored in a String Variable Month
Number of literals must match the number of elements in the array. If too few literals
are specified, the rest of the array is filled with blank characters. Also, a number being
stored in a char array must be specified as individual digits.
Program 17: Demonstrating String.
#include<stdio.h>
int main()
{
char stmame[15];
printf(“Enter the string:\n”);
scanf(“%s”, stmame);
printf(“\n The string entered is: %s\n”, stmame);
return 0;
Explanation:

stmame
s t r i n g & g g g g g g f! £ ‘\0’
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

There is no need to specify the number of characters to be entered when a “%s”


control field specification is used. The input function “%s” will read all the characters
that are entered upto the first blank or the first control character However, the storage
must be large enough that overflow does not occur. There is no need to specify the
null terminator when control field “%s” is used for the input of character strings as it
is automatically stored after the last valid character. Strings with embedded blanks
cannot be read using a “%s” control field.

5.6.4. Standard Library Functions


> A string is viewed simply as a sequence or linear array of characters. Various
string operations have been developed which are not normally used with other
kinds of array. Because C has no built-in facilities for manipulating entire arrays
(copying them, comparing them, etc.), it also has very few built- in facilities for
manipulating strings.
> In C there are no operators to manipulate strings because string is not a basic data
type. However, C has a rich library of string manipulation functions. They are in
the <string.h> library. This library must be included in the program in order to
use these functions. The most commonly used functions in the string library are:
strleaO Gets string length \ •:, ■' i" i -
streatO Concatenate two strings
strscatO Concatenate one string with part of another
strcpyO Copy a string
strcmpO Compare two strings
strrevO Reverse the string
strlwrO Changes the string from upper to lowercase
struprO Changes the string from lower to uppercase
strstr() Finds location of first substring in the string
5.6.4.I. strlen() Function
This function is commonly used to determine the length of a string. This is a single
argument function. The argument may be a string variable or a string literal.

The function strlen() returns an integer that is the count of the number of characters in
the string including embedded blanks and excluding the null terminator. Program 18
shows the use of this function.

Syntax
strlen(String);
Program 18: Finding String Length Using strlen() Function
#include<stdio.h> »
#include<conio.h> ■
#include<string.h> int main()

char stmamel[20] = "COMPUTERS"; char stmame2[20] =


"ORGANIZATION ; int n;

n = strlen(stmamel);
printf("The number of characters in stmamel is: %d\n", n);

n = strlen(stmame2); ^
printf("The number of character in stmame2 is: %d\n", n);
n = strlen("MOBILECCOMMERCE");

printf("The number of characters in string literal is: %d\n", n);

return 0;

strcpyO Function . . . ,
The function strcpyO is used to copy one string to another that is, it copies o one
variable of string type to another variable of string type.

Syntax
strcpy(Stringl, String2);

Program 19: String Copying Using strcpyO Function


#include<stdio.h>
#include<conio .h>
#include <string.h> void main()
{
char stringl[ ]="Hello world!";
char string2[20];
clrscrQ;
strcpy(string2, stringl);
printf("\nThe first string is Hello world\n");
printf("\nThe second string is empty\n");
printf("\nThe coping the string from stringl to string2 gives %s\n",string2);
getch(); ’’
}
Output

Explanation: The destination string is strcpy's first argument, so that a call to


strcpy mimics an assignment expression (with the destination on the left-hand side).

Note: To allocate string2 big enough to hold the string that would be copied to it. Also, at the top of
any source file where we’re using the standard library’s string-handling functions (such as strcpy)
we must include the line #include<string.h> which contains external declarations for these
functions.

5.6.4.2. strcat() Function


The process of combining of two strings together is technically termed as
concatenation. It is done by the library function called strcat(), which concatenates
strings. It does not concatenate two strings together and returns a third, but it appends
one string onto the end of another.
Syntax
strcat(Stringl, String2);

Program 20: String Concatenation by Using strcat() Function


#include<stdio.h>
#include<conio.h>
#include<string.h
> void main()
{
char string5[20] = "THAKUR
char string6[ ] = "PUBLICATIONS";
clrscr();
printf("\nThe first string entered is _THAKUR_\n");
printf("\nThe second string entered is _PUBLICATIONS_\n");
printf("\nConcating the strings gives\n");
printf(" % s\n", string5);
strcat(string5,string6);
printf("%s\n",string5);
getch();

Explanation: The first call to printf prints “_THAKUR_”, and the second one prints
“_PUBLICATIONS_” indicating that the contents of string6 have been tacked on to
the end of string5. The string5 is declared with extra space, to make space for the
appended characters.

5.6.4.3. strncat() Function


Another library function strncat() will perform a function similar to that done by
strcat(). However, stmcat() has three arguments - two strings (like strcat()) and an
integer specifying the number of characters of s2 to be added to the end of string si.

Syntax
strncat(sl, s2, n);
Program 21: String Concatenation by Using strcat() and strncat() Function.
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main() '
{
char si[80], s2[10];
int n;
clrscrQ;
printf("Enter two strings:");
scanf("%s%s", si, s2);
strcat(sl, s2);
printf("\nString built by strcat is %s.", si); printf("\nLength of the
string built by strcat is %d.", strlen(sl));

stmcat(sl, s2, 5);


printf("\nString built by stmcat using 5 characters is %s.\n", si);
return 0;
}

Explanation: When the above program is provided with inputs ‘thakur’ and
‘publishers’, the string built by strcat() is ‘thakurpublishers’ and the length of the
string is 16. After strncat() is used, the result in si is ‘thakurpublisherspubli’.

5.6.4.4. strcmp() Function


The strings in C are represented by arrays hence their comparison is done character by
character. The loop of this comparison is terminated only when there is a mismatch.
Syntax
int k = strcmp(strngl, strng2);

In this case, the character strings stmgl and stmg2 are compared character-by-
character. When unequal characters are found the order of the two strings is
determined. Based on the order of the two strings the comparison generates the
following results:
1) k > 0 positive number i.e., (stmgl after stmg2)
2) k = 0 positive number i.e., (stmgl identical to stmg2)
3) k < 0 negative number i.e., (stmgl before stmg2)

Program 22: String Comparison by Using strcmpO Function.


#include<string.h>
#include<conio.h>
#include<string.h> void main()
{
char stl[25],st2[30];
clrscr();
printf("\t ******* COMPARISON BETWEEN TWO STRINGS USING
STRCMP *******\n\n"); printf("\nENTER THE FIRST STRING: ");
gets(stl);
printf("\nENTER THE SECOND STRING: "); gets(st2);
printf("\n**** AFTER COMPARISON *****\n"); if(strcmp(stl,st2) == 0)
printf("\n\n\t[<— %s == %s —>] EQUAL STRINGS\n",stl,st2); else
printf("\n\n\t[<— %s != %s —>] DIFFERENT STRINGS\n'',stl,st2); getch();
}

Note: The strcmpO function does not return a Boolean, true/false, zero/nonzero answer; it
gives 0 as an output if the strings are equal else returns the difference in their ASCII codes.

5.6.4.5. strrev() Function


This function reverses a string entered by the user. For example, if a user enters a
string “reverse” then on reversing the string will be “esrever”.
Syntax
strrev(String);
Program 23: String Reversing Using strrev() Function.
#include<stdio.h>
#include<conio.h> .
#include<string.h> main()
{
char arr[ 100];
printf("Enter a string to reverse\n");
gets(arr);
strrev(arr);
printf("Reverse of entered string is \n%s\n",arr); return
0;
}
Output

5.6.4.6. strlwr() Function


This function takes string variable as its single argument and returns a pointer to
converted string. It converts the uppercase alphabet letters of the string to lower case
letters.
Syntax
strlwr(stl);
will convert the uppercase characters of string ‘stl’ to lowercase.
Program 24: Changing String to Lowercase Using strlwr() Function
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char strl[31]; clrscr();
printf("Enter any string of length <= 30:"); gets(strl);
printf("\nString after conversion: %s\n", strlwr(strl));
5.6.4.7. strupr() Function
This function takes string variable as its single argument and returns a pointer to
converted string. It converts the lowercase alphabet letters of the string to uppercase
letters.

Syntax
strupr(stl);
Program 25: Changing String to Uppercase Using strupr() Function.
#include<stdio.h> f
#include<conio.h>
#include<string.h>
void main()
{
char str 1 [31 ]; clrscr();
printf("Enter any string of length <= 30:"); gets(strl);
printf("\nString after conversion: %s\n", strupr(strl));
}

Output
■ DGSBox 0 74. Cpu speed: mas 100%cycles. Frameskip 0. Program: TC BMP
Enter any string of length <= 30:publication
String after conversion: PUBLICATION

5.6.4.8. strstr() Function


The function strstr() searches one string for the occurrence of another. It accepts two
strings as parameters and searches the first string for an occurrence of the second.
The function returns the memory address of the character in the first string, starting at
which the first occurrence of the second string is found.
Syntax
strstr(Stringl, String2);
Program 26: Search for a String
#include<stdio ,h>
#include<conio ,h>
#include<string ,h>
void main()
{
char strl[30], str2[30];
char *found; clrscr();
printf("Enter two strings:\n");
gets(strl);
gets(str2);
/* Search for str2 in strl */ found=strstr(str 1, str2);
printf("string2 is found at position %d in stringl\n",found-strl);

er two strings: come to C programming world!

ing2 is found at position 11 in stringl

Explanation: Here, the first string passed to strstr is, Welcome to C programming
world!. The second string is C. The function searches the first string for the given
second string. Though there are one instances of C in the first string, so it is
considered, and a pointer to the beginning of the match is returned.

5.7. IMPLEMENTAITONS WITHOUT USING


STANDARD LIBRARY FUNCTIONS
C program output can also be find out without using the standard library function,
that is, strlen(), strcat(), strcpyO, strcmp(), strlwrQ and etc. *
For understanding this, let’s we take some examples (or programs) illustrated
below.
Program 27: Finding String Length Without Using strlen().
#include<stdio.h>
#include<conio.h
> void mainQ {
chara[20]; int i; clrscr(); gets(a); i=0;
while(a[i]!='\0')
i++; //counts no of chars till encountering null char
printf("string length=%d",i);
getch();

Program 28: Concatenation of Two Strings Without Using strcat()


#include<stdio.h>
#include<conio.h> void main()
{
char str 1 [30] ,str2[30]; int
ll,12,i,j,k; clrscr();
printf("Enter Stringl:");
gets(strl);
printf("Enter String2:");
gets(str2);
//Finding Stringl Length {
j=0;
while(strl[j]!='\0')
j++;
ll=j;
}
//Finding String2 Length {
k=0;
while(strl [k] !='\0') k++;
12=k;
}
for(i=0;i<=12;i++)
{
strl[ll+i]=str2[i];
}
printf("%s",strl);
getch();
Program 29: Copying a string in c without using string function (strcpy)
#include<stdio.h>
#include<conio.h> void main()
{
char strl[100],str2[100];
int i=0;
clrscr();
printf("Enter any string: "); scanf("%s",strl); while(strl[i]!='\0’){ str2fi] = strl [i];
i++;
}
str2 [i]='\0';
printf("After copying: %s",str2); return 0;
}
Output

Program 30: C Program to Compare Two Strings Without Using strcmp().


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

int compare_string(char, char); main()


{
char first[100], second[100], result; clrscr();
printf("Enter first string\t"); gets(first);
printf("\nEnter second string\t"); gets(second);
result = compare(first, second); if(result == 0) printf("\nBoth strings are
same.\n"); else
printf("\nEntered strings are not equal.\n"); return 0;
int compare(char a[], char b[]) {
int c = 0;
while( a[c] == b[c] )
{
if( a[c] = '\0' II b[c] == '\0')
break; c++;
}
if( a[c] == '\0' && b[c] = 'NO') return 0; else return -1;
}

Program 31: Reversing a string in c without using string function (strrev).


#include<stdio .h>
#include<conio.h> int main()
{
char str[50]; char rev[50];
clrscr(); int i=-l,j=0;
printf("Enter any string : ");
scanf("%s",str);
while(str[++i] !='\0');
while(i>=0)
rev[j++] = str[—i];
rev[]]-\0';
printf("Reverse of string is : %s",rev);
return 0;
}

BjDOSBei0.74,Cpuspeed: mat 100%cydes, Frameskip 0, Program: TC


!nter ?,nt£$tring : Tliakitr Reyfirse of string is : rukahT

Program 32: C program to convert the string from Uppercase to Lowercase


Without Using strupr().
#include<stdio.h>
#include<conio .h> void lower_string(char*); main()
{
char string [100]; clrscr();
printf("Enter a string in Uppercase\n"); gets(string);
lower_string(string);
printf("String in lower case is \"%s\"\n", string); return 0;
}
void lower_string(char * string)
{
while(*string)
{
if ( *string >= 'A' && *string <= 'Z')
{
*string = *string + 32;
}
string++;
}

Output

Program 33: C program to convert the string from Lowercase to Uppercase


Without Using strupr().
#include<stdio.h>
#include<conio.h> int main(){ charstr[20]; int i; clrscr();
printf("Enter any string->");
scanf("%s",str); .
printf("The string is->%s",str);
for(i=0;i<=strlen(str);i++)
{
if(str[i]>=97&&str[i]<= 122) str[i]=str[i]-32;
} . printf("\nThe string in uppercase is-
>%s",str); return 0;
}

Explanation: ASCII value of ‘A’ is 65 while ‘a’ is 97. Difference between them is
97 - 65 = 32

So if we will add 32 in the ASCII value of ‘A’ then it will be ‘a’ and if will we
subtract 32 in ASCII value of ‘a’ it will be 'A'. It is true for all alphabets.

Note: In general rule:


Upper case character = Lower case character - 32
Lower case character = Upper case character + 32

5.8. PROGRAMS
Program 34: Find highest and lowest element in a single dimension array.
#include<stdio.h>
#include<conio.h>
void main()
{
int arraytSl^maXjinin; clrscr();
printf("\t ******* MAXIMUM & MINIMUM ELEMENT OF ARRAY

printf(" ELEMENTS OF AN ARRAY ARE:- \n"); for(x=0;x<5 ;x++)


{
scanf("%d",&array[x]);
} • max=array[0];
min=array[0]; for(x=0;x<5
;x++)
{
if(max<array[x])
{
max=array[x];
} ' if(min>array[x])
{
min=array[x];
}.
}
printf("\n\tMAXIMUM ELEMENT. %d",max);
printf("\n\tMINIMUM ELEMENT %d",min);
getch();

Program 35: Finding LCM and GCD.


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

void main()
{
int a[20], n, i, j, c, max, min; unsigned long prod; clrscr();
printf("\t\t****** LCM & GCD OF ELEMENTS OF ARRAYS ******\n\n");
printf("\tEnter the count of numbers: ");
scanf("%d",&n); ,
printf("\n\n\tEnter the entries: \n");
for(i=0;i<n;i++)
{ . scanf("%d",&c);
if(c>0) ..
a[i]=c;
else
{
printf(”Invalid Entry"); return;
}
}
max=a[0]; for(i=0;i<n;i++) if(a[i]>=max)
max=a[i];
min=a[0]; =
for(i=0;i<n;i++) if(a[i]<min) min=a[i];
for(i=0,prod=l ;i<n;i++) prod=prod*a[i];
for(i=max;i<=prod;i+=max)
{
c=0;
for(j=0;j<n;j++)
if(i%a[j]=0)
c+=l;
if(c==n) __
{ ' ' " printf("\tThe LCM of the nos:
%d\n",i); break;
}
} , for(i=min;i>0;i—)
{
if (min%i==0)
{
c=0;
for(j=0;j<n;j++)
if(a[j]%i==0)
c+=l;
}
if(c==n)
{
printf("\tThe GCD of the nos: %d\n",i);
break;
}
1
} ^ getch();

}V
Output
SDl_app
****■*•«• LCM « GCD OF Ef.EMEM
Enter- the count of numbers: 3

Enter th« entries:

The LCM of the nos:' 10172 The


GCD of the nos: 2

Program 36: Menu Driven Program for encoding and decoding of String.
#include<stdio.h>
#include<conio.h>
#include <string.h>

* int main() {

char Stringl [100], String2[100], String3[100]; int Index;

printf("Enter the string:\n\n"); gets(Stringl); //Accept String from User


i.
for(Index=0;Index<strlen(S tring 1) ;Index++)
{

String2[Index]=String 1 [Index]+1;// encoding }


printf("\nThe Encoded String is:\n\n"); puts(String2);

for(Index=0;Index<strlen(String2);Index++)
{

String3[Index]=String2[Index]-1 ;//decoding

}
printf("\nThe Decoded String is:\n\n"); pubs.String3);

geteh* K return 0;
S
J
Output
CADev- CppXExam plesW.

Program 37: Matrix Multiplication.


#include<stdio.h>
#include<conio ,h> int main()
{
int A[ 10] [ 10] ,i,j,k,B [ 10] [ 10],C [ 10] [ 10] ,r 1 ,c 1 ,r2,c2;
i-

printfCEnter number of rows and columns of matrix A \n");


scanf("%d%d",&rL&cl);
printf("Enter number of rows and columns of matrix B\n");
scanf("%d%d",&r2,&c2);
if(r2==cl)
{
printf("Enter rows and columns of matrix A\n");
printf("Row wise\n");
for(i=0;i<rl;i++)
{
for(j=0;j<cl;j++)
scanf("%d",&A[i][j]);
}

printf("You have entered the matrix A as follows:\n");

for(i=0;i<rl;i++)
{
for(j=0;j<c 1 ;j++)
printf("%d\t",A[i][j]);
printf("\n");
}
• „ printf("Enter rows and columns of B matrix \n");
printf("Again row wise\n");

for(i=0;i<r2;i++)
{
tO uinpj :()qoj3§ {
:(„3uop aq jouubo uopBoijdpinp^ xujBpvJjjuud
}
asp
{
{
X„u\„)jjuud
{
X[f]M3‘uJ\P%.,)jJupd
{
/* ■ to] [3] a* [z\ [0]v+[o] [ 1 ] a* [ 1 ] to] v+fo] to] a* to] [oJv=[o]
toto*/
i[nwa*MMv=+tnmD
}
(++*IJ>5I:O=51)-TOJ
;0=[f][?]D

}
(++[^o>po=DJOJ
}
(++i:ij>i:o=i)jqj

/*£eVX£IB+£3yxz:iB+ei yxT IB 3£Vxen?+^VX3XB+2iYxnB I£V*£


IB+1 ZV*ZIB+l I V x l lB*/ ;(„u\:SMonoj sb si uoiiBoijdppiui aip jo
qnsai aqj^j.puud ;(„u\ xujbui 3AoqB aqj qjoq /qdiqnui 3M
MOjsjJjiuud

{
% i(„n\.,)fl«pd
i([n[i]a‘„J\P%,.)jJaud
(++f^3>f;o=f)-I0i
}
(++T‘2I>T‘0==T)JOJ
t^uysMoijoj sb g xujbui aqj paiajua 3ABq noj^Jjjuud

{
i([Q[T]av‘,.p%,.)jo8os
(++r.£3>no=0°j
}
Output
• C:\Dev-Cpp\Examples\VTU C\matrix_multiply,exe
nter nunber of rows and coiunns of matrix A

S nter number of rows and colunns of Fidtrix B


i
nter rows and columns of natrix A
ou wise

ou have entered the matrix (1 as follows ■ 0


0 .
Inter rows and columns of B matrix Itfain row wise

ou have entered the matrix B as follows:


20
1 2 . ow we multiply both the above
matrix he result of the multiplication is as follows 2 0 2
0

Program 38: Saddle point of a Matrix.


#include <stdio ,h>
#include <conio.h>
#define ROW 10 #define COL 10

int main() {
int i, j, k, n, min, max, matrix[ROW][COL], pos[2][2];
/* get the order of the matrix from the user */
printf("Enter the order of the matrix:"); scanf("%d",
&n);

/* get the entries for the input matrix from the user */
printf("Enter your entries for the input matrix:\n"); for (i
= 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &matrix[i][j]);
}
}
printf("The input matrix is:\n"); for (i = 0; i < n; i++) {
printf("\n");
for (j = 0; j < n; j++) {
printf("\t%d", matrix[i][j]);
}

/* find the saddle points in the given matrix */


for (i = 0; i < n; i++) { min = matrix [i] [0]; for
(j = 0; j < n; j++) {
if (min >= matrix[i][j]) { min
= matrix[i][j]; pos[0][0]
= i; pos[0][l] = j;
}
}
j =pos[0][l]; max =
matrix[0][j]; for (k = 0;
k < n; k++) {
if (max <= matrix[k][j]) { max
= matrix[i][j]; pos[l][0] =
k; pos[l][l] = j;
}
}
/* saddle point - minimum of a row and maximum of the column */ if
(min == max) {
if (pos[0][0] == pos[l][0] &&
Pos[0][l] == pos[l][l]) { printf("\n\nSaddle
point (%d, % d ) : %d\n", pos[0][0],
pos[0][l], max);
}
}
}
getch(); return 0;
}
Output
C:\Dev-C pp\Examples\VTU C\Saddfe_point„
;n^er the order of the natrix:3 oter y° ul' entries for the input
matrix:

he input matrix is;

addle point <2, 0>


Program 39: Magic Square.
#include<stdio,h>
#include<conio.h> int main()
{ .. int sqr[25] [25]={(0)} ,n,i,j ,k,p,q;
//clrscr();
printf("enter size of magic squre:"); label:
scanf("%d",&n); if(n%2 !=1 lln>=25)
{
printf("Enter the odd value in the range of 25\n");
goto label;
}
i=0;
j=(n)/2;
sqr[i][j]=l;
for(k=2;k<=(n*n) ;k++)
{
p=i-l<0?n-l : i-1;
q=(j+l)%n;
if(sqr[p][q]==0)
{
i=p;
j=q;
}
else
i++;
sqr[i][j]=k;
}
printf("\nHere is the magic square\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf("%d\t",sqr[i][j]);
printf("\n");
}
getch(); return 0;
}
Output __________________ _____
C:\Dev-Cpp\ExampIesSVTU CVnagi...
enter s ize o F magic squre:5
Here is the rmgic square
17 24 1 8 15
23 5 V 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9

5.9. EXERCISE
1) What is an array? Explain the features of an array and their uses.
2) In what ways does an array differ from an ordinary variable? What advantage is there in
defining an array size in terms of symbolic constant rather than a fixed integer constant?
3) Can an array be used as an argument to a function? If yes, explain with examples.
4) Explain the concept of multidimensional arrays in ‘C’ Language.
5) What do you understand by strings? How do you declare a string?
6) Write a program to copy one string into another. .
7) Explain the functions of the following:
i) StrcpyO
ii) Strlen()
iii) Strcat()
8) Can an array of pointers to string be used to collect strings from the keyboard? Justify your
answer.
9) How to find the end of the string?
10) What is the difference between three representations a, 'a' and "a"?
11) How do we read string including blank space?
12) Can we use scanf() to read string with blank spaces? If so how?
13) Declare two symbolic constants for the order of a matrix. Declare a matrix of that order.
Populate the matrix and display the same in the matrix form.
14) What will be the output of the following programs:
i) main()
{
int num[26], temp;
num[0] = 100;
num[25] = 200;
temp = num[25];
num[25] =
num[0]; num[0] =
temp;
printf("\n%d %d", num[0], num[25]);
}
ii) main()
{
int array[26], i; for(i=0; i<=25; i++)
{ . array[i] = 'A' + i;
printf("\n%d %c", arrayfi], array[i]);
},
iii) main()
{
int sub[50], i; for(i=0; i<=48; i++);
{
sub[i] = i;
printf("\n%d", sub[i]);
}
15) Write a function to multiply two arrays element-by-element, store the result in another array,
and return that array to the calling program. Do not pass individual elements.
16) Write a program to multiply any two 3x3 matrix.
17) Write a program to get a 2-digit number from the user and display it in words, e.g., if user
supplies ‘45’ then program should display ‘forty five’.
18) Write a program to transpose a matrix.
19) Write a program to read in an array of 10 integers and sort that array into ascending or
descending order depending upon the user s choice.
20) Write a function to receive an array containing real numbers, sum the numbers, and return the
sum to the calling program. Do not pass individual array elements.
21) Is 2-D array be the combination of 1-D array? If yes explain with the help of suitable example?
22) What do you understand by row-major implementation and column-major implementation of 2-
D array?
}
23) Write a program that reads a string from the keyboard and determines whether the string is a
palindrome or not. (A string is a palindrome if it can be read from left and right with the same
meaning. For example, Madam and Anna are palindrome strings. Ignore capitalisation).
24) Write a program which will read a text and count all occurrences of a particular word.

Das könnte Ihnen auch gefallen