0% found this document useful (0 votes)
10 views

Unit II Arrays and Strings in C

Uploaded by

Savitha Raja
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Unit II Arrays and Strings in C

Uploaded by

Savitha Raja
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

UNIT II ARRAYS AND STRINGS:

Introduction to Arrays: Declaration, Initialization – One dimensional array –


Two dimensional arrays - String operations: length, compare, concatenate, copy –
Selection sort, linear and binary search.

Arrays - C Programming:
Array is a collection of same data type elements under the same variable identifier
referenced by index number. Arrays allow you to store group of data of a single
type.

ARRAYS:
In the early the values are stored in a variable of primary data types. The
disadvantage is only one value can be stored in a variable at a time. Therefore to
store more than one value, then more than one variable have to be declared. An
additional variable can be declared to store or read two or three values. Imagine
storing the register numbers of students of a college in several variable names to
store the register number of the students. Then the program becomes unreadable
and complex. To simplify that array can be used by just declaring one variables of
type array.
Consider the following example of data type intreg[1000], this means the variable
name „reg‟ can store up to 1000 values. The values can be read, element by
element. Therefore to store a large set of data of same type array is the choice.
Array is a derived data type. It is very effective when working with large number
of data of same data type or different data types.
Definition:
Array is a collection of same data type elements under the same variable identifier
referenced by index number. Arrays allow you to store group of data of a single
type.
Consider the following example:
Intx,y,z;
X=10;y=20;z=30;
The above statements can be rewritten using array form
int x[3];
x[0]=10; x[1]=20; x[2]=30;
When the number of variable is less the statement may not look confusing or
difficult. Now consider the ollowing example.
int y[60];
The array y can store up to 60 values in its elements. The structure and location
value in the array is similar to matrix. Now it is clear that it is not good practice to
declare 60 variables or array y.
Arrays are classified as follows:
1. One dimensional array
2. Two dimensional array
3. Multidimensional array
4. Dynamic array

1 One Dimensional Array


It is similar to matrix with only one column but multiple rows. This type o array is
useful when working with only set of data at a time.
Declaring One Dimensional Array:
It is similar to declaring any other primary data type except, the number element
must specified or an array in bracket.
int z[5]; loat s[10]; double w[6];
char t[4];
The arrays declared as shown. The numbers inside the bracket is the number of
elements for that variable. There ore z can store 5 values, s 10 values, w 6 values.
The only difference for character array t; is that the last element in the array must
be allowed for NULL value, therefore remaining 3 elements of t can be any
character including NULL.
Assigning One Dimensional Array:
int z[5]
z[0]=10;
z[1]=20;
z[2]=30;
z[3]=40;
z[4]=50;
The values are assigned elements by element in the array.
Note: The array element start with 0 NOT 1
float z[10];
z[2]=11.11;
z[5]=66.66;
z[8]=45.90;
In the above the element 2, 5, and 8 are assigned values but the other elements are
not assigned any values. In such case the remaining element will be assigned zero.
Therefore for numeric array, When the value is assigned to fewer elements the
remaining elements will be assigned zero by the compiler.
Char t[4];
t[0]=‟a‟;
t[1]=‟b‟;
t[2]=‟c‟;
t[3]=‟d‟;
The last element t[3] is assigned „d‟, as we discussed earlier the element or
character array must be provided for NULL value. Here „d‟ is assigned to the
element the compiler will not give error during compilation but there will be error
in the program during run time.
Now consider this example:
Char t[4];
t[0]=‟a‟;
t[1]=‟b‟;
In this example the 3rd element and 4th element will be NULL. Therefore when the
value is assigned to fewer elements the element will be assigned NULL by the
compiler or character array whereas or numeric or numeric array zero will be
assigned.
Initializing One Dimensional Array
Method 1;
int z[5] = {11,22,33,44,55}
char t[6] = {„k‟,‟i‟,‟n‟,‟g‟}
All the array elements are assigned value. The last element or the character arrays
must be provided for NULL character.
Method 2:
intz[5]={11,22,33};
char t[6]={„a‟,‟b‟.‟p‟};
Only first three elements are assigned values the remaining elements will be
assigned zero or integer data type. The remaining element or character array will
be assigned NULL.
Method 3:
int z[5]={0};
char t[6]=”apple”;
All the array elements are assigned zero. The character array can also be initialized
as above.
Method 4:
int z[] = {11,22,33};
char t[]=’apple’;
Since array size is not defined. The array must be initialized, therefore the size of
the array will be same the number of values assigned. Therefore the integer array
size for this example in three since three value are provided in the initialization.
The array size for character array t is 6, five for the character and one for the
NULL terminator.
To assign zero to a specific element the location of the element must be specified.
Thus the array values are assigned sequentially. To assign value element by
element then assigning method must be adopted.
z[5]={0,22,33,44,55};
z[5]={0,22,33,0,55};
Arrays can be read/written by any of the looping statements.
Assigning value to array by program:
intx[5],i;
for(i=0;i<5;i++)
{
scanf(“%d”,&x[i]);
}
Reading value to array by program:
intx[5],i;
for(i=0;i<5;i++)
{
printf(“%d”,x[i]);
}
Remember, the initial value or array must start with zero and the condition part
must be (<) less than sign, and the value must be the size of array, and the
increment must by one, to assign value element by element.

2 Two Dimensional Arrays:


It is similar to matrix with multiple rows and columns. This types of array is useful
when working with more than one set o data at a time.
Declaring Two Dimensional Arrays:
Syntax:
Data_typevar_name[r_s][e_s];
Eg: intmarks[10][3];
The array has 10 rows and 3 columns. The values in the array are located by row
and column, just like in matrix. Similar to one dimensional array the row and
column elements start from zero not one.
Assigning values to Two Dimensional Arrays:
C0 C1 C2
R0 11 22 33
R1 44 0 55
R3 0 2 4
The above example has 3 rows and 3 columns. The value of the matrix can be
assigned to the array as follows.
int re[3][3];
re[0][0]=11;re[0][1]=22;re[0][2]=33;
re[1][0]=44; re[1][1]=2; re[1][2]=4;
re[2][0]=0;re[2][1]=2;re[2][2]=4;
Initializing Two Dimensional Arrays:
Methods 1;
Consider the following example for the matrix to be initialized:
int re[3][3] = {11,22,33,44,0,55,0,2,3};
In this example the first row will be 11, 22, and 33; the second row 44, 0, and 55;
and the third row 0, 2, and 4. Therefore it is clear that the values will be assigned in
row wise.
Method 2:
The method 1 can be written as follows to get the same result.
int re[3][3] = {{11,22,33},{44,0,55},{0,2,4}};
Here each braces {} represents each row, starting from the first row. The method
two can be written to look like matrix without any change in the syntax;
intre[3][3]={{11,22,33},{44,0,55},{0,2,4}};
Method 3:
The method 1 can be written as follows to get the same result.
int re[][3] = {{11,22,33},{44,0,55},{0,2,4}};
In this example the row will be set to 3 since row size is not specified the number
of rows will be decided by the initial values.
Method 4:
int re[3][4] = {{33},{0,55,0},{0}}
In this method the value in the array will be as follows
re[0][0]=33; re[0][1]=0; re[0][2]=0;
re[1][0]=0; re[1][1]=55; re[1][2]=0;
re[2][0]=0; re[2][1]=0; re[2][2]=0;
Method 5:
intrc[3][3]={{0},{0},{0}};
intrc[3][3]= {0,0,0};
In this method the value in the entire array element will be zero.
re[0][0]=0; re[0][1]=0; re[0][2]=0;
re[1][0]=0; re[1][1]=0; re[1][2]=0;
re[2][0]=0; re[2][1]=0; re[2][2]=0;
Assigning value to array elements by program:
intre[3][3],i,j;
for(i=0;i<3;++i)
{
for(j=0;j<3;++j)
{
scanf(“%d”,&re[i][j]);
}
}
Reading value from array elements by program:
int re[3][3],i,j;
for(i=0;i<3;++i)
{
for(j=0;j<3;++j)
{
printf(“%d”,re[i][j])
}
}
Remember for both row and column, the initial value or array must start with zero
and the condition part must be less than sign(<) and value must be the size of array,
and the increment must by one, to assign value element by element.
Advantages of Array:
1. It reduces the programming length significantly.
2. It has better control over program for modiication.
3. Coding is simple, efficient, and clear.
4. It can handle large set of data with simple declaration.
Rules of Array:
1. It does not check the boundary.
2. Processing time will increase when working with large data because of increased
memory.
3. The array element start with zero not 1.
4. Character array size must be one element greater than data for NULL value.
5. One variable for control structure is required to assign and read value to one
dimensional array.
6. Two variable for control structures are required to assign and read value to two
dimensional arrays.
7. No two arrays can have the same name but arrays and ordinary variable can be
assigned the same name.

Strings - C Programming:
String is the collection of characters. It can be represented by 1-d arrays. Header
file used is string.h.
String
String is the collection of characters. It can be represented by 1-d arrays. Header
file used is string.h.
String Declaration:
Datatypevariable_name[size];
Eg: char sar[30];
String Initialization:
Datatype variable_name[size]=string;
Eg: char sar[30]={“Niro”};

1 Built in Sting functions/ String Operation/ Sting Manipulation Function:


There are several string functions to work with string variables and its values.
These functions are available C header file called string.h. Consider the
following exa,ple:
Char string1[15]=”Sriram”;
Char string2[15]=”College”;
Copying String
Strcpy(string1,string2);
This function copy‟s the value of string2 to string1. Now the string1 be
“College”. To add the string2 to string1 the size of the string1 must be sufficient
enough to fit the value of string2. This function will replace the existing value
string1 with string2. Now string1 and string2 are “College”.
String comparison[Case Sensitive]
Strcmp(string1,string2);
This function compares the value from string2 with string1. If both the string1
and string2 are exactly the same then the function will return zero or else it will
return some positive or negative value. For the above example the function will
return negative of positive value. Here string1 and string2 will not change.
Non-Case Sensitive:
strcmpi(string1,string2);
Concatenation Sting
strcat(string1,string2);
Copying String
strcpy(string1,string2);
This function copy‟s the contents of one string into another string.
Find a value in sting
strstr(string1, string2);
This function will find the value of string2 in string1. Assume string1 as
“Apple” and string2 as “Ap” now the function will return position of first
occurrence of “Ap”, since “Ap” is found in “Apple”.
Reversing a string
strrev(string1);
This unction reverse the data o string1 and stores it in string1.
Length of String
Strlen(string1);
This function will return length of the string. For the above example it returns
8.
Convert Uppercase to Lower case
strlwr(string1);
Convert Lower case to Uppercase
strupr(string1);
Example: Palindrome of string data
//To check whether the data is palindrome
#include<stdio.h>
#include<conio.h>
#include<string.h>
int r;
char s1[15],s2[15];
void main()
{
clrscr();
printf(“Enter anything:”);
scanf(“%s”,s1);
strcpy(s2,s1); //copy‟s s1 to another variable s2
strrev(s2); //reverse the value of s2
scanf(“%s\n”,s1);
scanf(“%s\n”,s2);
r=stremp(s1,s2);
if(r==0)
printf(“It is a Palindrome %s\n”,s1);
else
printf(“It is not a Palindrome %s\n”,s1);
getch();
}
1-D ARRAYS
P_1: Accept 5 numbers & STORE IN Array also print the numbers in the
Array.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5];
printf(“\n Enter the element:”);
for(i=0;i<5;i++)
{
scanf(“%d”,&a[i]);
}
printf(“\n The elements in the array are:”);
for(i=0;i<5;i++)
{
printf(“%d”,a[i]);
printf(“\n”);
}
getch();
}
P_2: Reversing the elements in the Array
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i;
printf(“\n Enter the element:”);
for(i=0;i<10;i++)
{
scanf(“%d”,&a[i]);
}
printf(“\n The elements in the array are:”);
for(i=9;i<=0;i--)
{
printf(“%d”,a[i]);
printf(“\n”);
}
getch();
}
P_3: To find the sum and average of elements in the Array.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],I,sum=0;
floatavg=0;
printf(“\n Enter the element:”);
for(i=0;i<20;i++)
{
scanf(“%d”,&a[i]);
}
printf(“\n The elements in the array are:”);
for(i=0;i<20;i++)
{
sum=sum+a[i];
}
printf(“\n The Sum of elements in the array is %d”,sum);
avg=sum/20;
printf(“\n The Average of elements in the array is %f”,avg);
getch();
}
P_4: Find the maximum of elements present in the array
#include<stdio.h>
#include<conio.h>
void main()
{
inti=0,x,a[5]={32,44,11,3,6};
clrscr();
x=a[0];
for(i=0;i<5;i++)
{
If(x<a[i])
x=a[i];
}
printf(“\n The value is %d.”,x);
getch();
}
P_5: Program to arrange an array of elements in Ascending
order.[BUBBLE SORT]
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,n,j,t;
clrscr();
printf(“Enter size of array:”);
scanf(“%d”,&n);
printf(“Enter array elements:”);
for(i=0;i<n;i++)
{
printf(“array before sorting\n”);
for(i=0;i<n;i++)
{
Printf(“%d\n”,a[i]);
}
for(i=0;i<n;i++)
{
for(j=i;j<n;j++)
{
If(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
printf(“\n after sorting\n”);
for(i=0;i<n;i++)
{
Printf(“%d\n”,a[i]);
}
getch();
}
P_6: Program to arrange an array of elements in Ascending
oreder.[Quicker sort]
#include<stdio.h>
#include<conio.h>
void quicksort(int [10],int,int);
void main()
{
int x[20], size,i;
printf(“Enter size of the array: ”);
scanf(“%d”,&size);
printf(“Enter %d elements:”, size);
for(i=0;i<size;i++)
scanf(“%d”,&x[i]);
quicksort(x,0,size-1)
printf(“Sorted elements:”);
for(i=0;i<size;i++)
printf(“%d”,x[i]);
return 0;
}
void quicksort(int x[10],int first, int last)
{
intpivot,j,temp,i;
if(first<last){
pivot=first;
i=first;
j=last;
while(i<j){
while(x[i]<=x[pivot]&&i<last)
i++;
while(x[j]>x[pivot])
j--;
if(i<j){
temp=x[i];
x[i]=x[j];
x[j]=temp;
}
}
temp=x[pivot];
x[pivot]=x[j];
x[j]=temp;
quicksort(x,first,j-1);
quicksort(x,j+1,last);
}
}
////[2-Dimensional Arrays]///
P_1: Initializing 2-D Array.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5],i,j;
printf(“\n Enter the element:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
printf(“Matrix[%d][%d]”,i,j);
scanf(“%d”,&a[i][j]);
}
}
printf(“\n Matrix is:”);
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
printf(“%d”,a[i][j]);
printf(“\n”);
}
getch();
}
P_2: Program to demonstrate matrix multiplication.
Algorithm-Multiplication of two matrixes:
Rule: Multiplication of two matrixes is only possible if first matrix has size m X
n and other matrix has size n x r. Where m, n and r are any positive integer.
Multiplication of two matrixes is define as
For example:
Suppose two matrixes A and B of size of 2x3 and 2x3 respectively:

Program:
P_1: Initializing 2-D Array.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,k,row1,col1,row2,col2;
clrscr();
printf(“\n Enter array1 size ”);
scanf(“%d%d”,&row1,&col1);
printf(“\n Enter array2 size ”);
scanf(“%d%d”,&row2,&col2);
if(row2!=col1)
{
printf(“Wrong choice entered”);
getch();
exit(0);
}
else
{
printf(“Enter elements”);
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“Enter elements 2”);
for(i=0;i<row2;i++)
{
for(j=0;j<col2;j++)
{
scanf(“%d”,&b[i][j]);
}
}
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
c[i][j]=0;
for(k=0;k<row2;k++)
{
c[i][j]=c[i][j]+(a[i][j]*b[i][j])
}
}
}
printf(“REQUIRED MATRIX”);
for(i=0;i<row1;i++)
{
for(j=0;j<col2;j++)
{
printf(“\n%d”,c[i][j]);
}
printf(“\n”);
}
getch();
}
}
P_3: Program to demonstrate matrix addition.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],b[3][3],c[3][3],i,j,row1,col1,row2,col2;
clrscr();
printf(“\n Enter array1 size ”);
scanf(“%d%d”,&row1,&col1);
printf(“\n Enter array2 size ”);
scanf(“%d%d”,&row2,&col2);
printf(“Enter the First matrix :”);
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“\n Enter the Second matrix: ”);
for(i=0;i<row2;i++)
{
for(j=0;j<col2;j++)
{
scanf(“%d”,&b[i][j]);
}
}
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf(“\n The Addition of two matrix is \n”);
for(i=0;i<row1;i++)
{
printf(“\n”);
for(j=0;j<col1;j++)
{
printf(“%d\t”,c[i][j]);

}
}
return 0;;
}
P_4: Program to matrix transpose
/*2-D Transpose*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10],row,col,i,j;
clrscr();
printf(“\n Enter row size ”);
scanf(“%d”,&row);
printf(“\n Enter column size ”);
scanf(“%d”,&col);
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf(“\n matrix [%d][%d]”,i,j);
scanf(“%d”,&a[i][j]);
}
}
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
b[i][j]=a[i][j];
}
}
printf(“\n Transpose of given Matrix: ”);
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf(“\n%d”,b[i][j]);
}
}
getch();
}
P_5: To search the location of given data in the array / Linear Search
[SEARCHING]
#include<stdio.h>
#include<conio.h>
void main()
{
inti,n,data,a[20],f=0;
printf(“\n Enter the Array Capacity: ”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
printf(“\n Enter the %d Data: ”,i+1);
scanf(“%d”,&a[i]);
}
}
printf(“\n Enter the data to be searched:”);
scanf(“%d”,&data);
for(i=0;i<n;i++)
{
if(data==a[i])
{
printf(“\n Data is found in %d location”, i+1);
f=1;
}
}
if(f!=1)
{
printf(“\n Data not Found:”);
}
getch();
}

P_6: Binary Search in C:


#include<stdio.h>
#include<conio.h>
void main()
{
inti, first,last, middle, n, search, array[100];
printf(“\n Enter number of elements\n ”);
scanf(“%d”,&n);
printf(“\n Enter %dintegers\n”,n);
for(i=0;i<n;i++)
scanf(“%d”,&array[i]);
printf(“\n Enter value to find\n” );
scanf(“%d”,&search);
first=0;
last=n-1;
middle = (first+last)/2;
while(first<=last)
{
if(array[middle]<search)
first=middle+1;
else if(array[middle]>search)
{
last=middle+1;
}
else
{
printf(“%d found at location %d.\n”,search,middle+1);
if(first>last)
printf(“Not found! %d is not present in the list. \n”,search);
return 0;
}

String
String is the collection of characters. It can be represented by 1-d arrays. Header
file used is string.h.
String Declaration:
Datatypevariable_name[size];
Eg: char sar[30];
String Initialization:
Datatype variable_name[size]=string;
Eg: char sar[30]={“Niro”};
1 Built in Sting functions/ String Operation/ Sting Manipulation Function:
There are several string functions to work with string variables and its values.
These functions are available C header file called string.h. Consider the
following exa,ple:
Char string1[15]=”Sriram”;
Char string2[15]=”College”;
Copying String
Strcpy(string1,string2);
This function copy‟s the value of string2 to string1. Now the string1 be
“College”. To add the string2 to string1 the size of the string1 must be sufficient
enough to fit the value of string2. This function will replace the existing value
string1 with string2. Now string1 and string2 are “College”.
String comparison[Case Sensitive]
Strcmp(string1,string2);
This function compares the value from string2 with string1. If both the string1
and string2 are exactly the same then the function will return zero or else it will
return some positive or negative value. For the above example the function will
return negative of positive value. Here string1 and string2 will not change.
Non-Case Sensitive:
strcmpi(string1,string2);

Concatenation Sting
strcat(string1,string2);
Copying String
strcpy(string1,string2);
This function copy‟s the contents of one string into another string.
Find a value in sting
strstr(string1, string2);
This function will find the value of string2 in string1. Assume string1 as
“Apple” and string2 as “Ap” now the function will return position of first
occurrence of “Ap”, since “Ap” is found in “Apple”.
Reversing a string
strrev(string1);
This unction reverse the data o string1 and stores it in string1.
Length of String
Strlen(string1);
This function will return length of the string. For the above example it returns
8.
Convert Uppercase to Lower case
strlwr(string1);
Convert Lower case to Uppercase
strupr(string1);

Example: Palindrome of string data


//To check whether the data is palindrome
#include<stdio.h>
#include<conio.h>
#include<string.h>
int r;
char s1[15],s2[15];
void main()
{
clrscr();
printf(“Enter anything:”);
scanf(“%s”,s1);
strcpy(s2,s1); //copy‟s s1 to another variable s2
strrev(s2); //reverse the value of s2
scanf(“%s\n”,s1);
scanf(“%s\n”,s2);
r=stremp(s1,s2);
if(r==0)
printf(“It is a Palindrome %s\n”,s1);
else
printf(“It is not a Palindrome %s\n”,s1);
getch();
}

UNIT IV STRUCTURES AND UNION

Structure - Nested structures – Pointer and Structures – Array of structures – Self


referential structures – Dynamic memory allocation - Singly linked list – typedef –
Union - Storage classes and Visibility.

UNIT V FILE PROCESSING

Files – Types of file processing: Sequential access, Random access – Sequential


access file Random access file - Command line arguments.

You might also like