Unit Ii
Unit Ii
UNIT - II
ARRAYS AND STRINGS Introduction to Arrays: Declaration, Initialization – One
dimensional array – Example Program: Computing Mean, Median and Mode - Two
dimensional arrays – Example Program: Matrix Operations (Addition, Scaling,
Determinant and Transpose) - String operations: length, compare, concatenate, copy –
Selection sort, linear and binary search
2.1 Introduction to Arrays
An array is a collection of data that holds fixed number of values of same type. For
example: if you want to store marks of 100 students, you can create an array for it.
float marks[100];
The size and type of arrays cannot be changed after its declaration.
2.1.1 Declaration
How to declare an array in C?
data_type array_name[array_size];
For example,
float mark[5];
Here, we declared an array, mark, of floating-point type and size 5. Meaning, it can
hold 5 floating-point values.
Elements of an Array and How to access them?
You can access elements of an array by indices.
Suppose you declared an array mark as above. The first element is mark[0], second
element is mark[1] and so on.
TPGIT/CSE 1
CS8251 Dept of CSE Programming in C
Here,
mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9
Example: C Arrays
// Program to find the average of n (n < 10) numbers using arrays
#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;
printf("Enter n: ");
scanf("%d", &n);
for(i=0; i<n; ++i)
{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
TPGIT/CSE 2
CS8251 Dept of CSE Programming in C
sum += marks[i];
}
average = sum/n;
return 0;
}
Output
Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39
int testArray[10];
TPGIT/CSE 3
CS8251 Dept of CSE Programming in C
4 {
5 int i,number[5];
6 clrscr();
7 printf(“Enter 5 number \n”);
8 for(i=0;i<5;i++)
9 scanf(“%d”,&numbers[i]);
10 printf(“Array elements are \n”);
11 for(i=0;i<5;i++)
12 printf(“%d\n”,numbers[i]);
13 getch();
14 return 0;
15 }
Output :
4
6
7
3
2
Array elements are
4
6
7
3
2
It’s a very common error to try to refer to non-existent numbers[ 5], element. C does not
do much hand holding. It is invariably up to the programmer to make sure that
programs are free from errors. This is especially true with arrays. C does not complain if
you try to write to elements of an array which do not exist!
For example: If you wrote:
numbers[ 5 ], = 6;
C would happily try to write 6 at the location which would have corresponded to the
sixth element, had it been declared that way. Unfortunately this would probably be
memory taken up by some other variable or perhaps even by the operating system. The
result would be either:
The value in the incorrect memory location would be corrupted with
unpredictable consequences.
The value would corrupt the memory and crash the program completely!
The second of these tends to be the result on operating systems with proper memory
protection. Writing over the bounds of an array is a common source of error. Remember
that the array limits run from zero to the size of the array minus one.
Out of bounds access :
I would be doing well, that really shows the range of valid indices, please check often.
10 When the number of elements, all the indices of 10 or more is illegal. Also, whether
any size of negative indices is also illegal.
These errors are detected at compile time is not. It is an error at run time. However,
there is no guarantee that the error reliably. Sometimes works correctly (seems to be
moving.) This is the “luck ran” instead of “bad luck worked” so, please, as no doubt.
TPGIT/CSE 4
CS8251 Dept of CSE Programming in C
The best way to see these principles is by use of an example, so load the program and
display it on your monitor.
The elements of an array can also be initialized in the array declaration by following the
declaration with an equal sign and a comma-separated list (enclosed in braces)
of initializers.
Example:
1 #include <stdio.h>
2 #include <conio.h>
3 int main( )
4{
5 char name[7]; /* define a string of characters */
6 name[0] = 'A';
7 name[1] = 's';
8 name[2] = 'h';
9 name[3] = 'r';
10 name[4] = 'a';
11 name[5] = 'f';
12 name[6] = '\0'; /* Null character - end of text */
13 name[7] = ‘X’;
14 clrscr();
15 printf("My name is %s\n",name);
16 printf("First letter is %c\n",name[0]);
17 printf("Fifth letter is %c\n",name[4]);
18 printf("Sixth letter is %c\n",name[5]);
19 printf("Seventh letter is %c\n",name[6]);
20 printf("Eight letter is %c\n",name[7]);
21 getch();
22 return 0;
23 }
The following program initializes an integer array with five values and prints the array.
1 #include <stdio.h>
2 #include <conio.h>
3 int main()
4{
5 int numbers[]={1,2,3,4,5};
6 int i;
7 clrscr();
8 printf("Array elements are\n");
9 for(i=0;i<=4;i++)
10 printf("%d\n",numbers[i]);
11 getch();
12 return 0;
13 }
If there are fewer initializers than elements in the array, the remaining elements are
initialized to zero. For example, the elements of the array n could have been initialized
to zero with the declaration
int n[ 10 ] = { 0 };
which explicitly initializes the first element to zero and initializes the remaining nine
TPGIT/CSE 5
CS8251 Dept of CSE Programming in C
elements to zero because there are fewer initializers than there are elements in the array.
It is important to remember that arrays are not automatically initialized to zero. The
programmer must at least initialize the first element to zero for the remaining elements
to be automatically zeroed. This method of initializing the array elements to 0 is
performed at compile time for static arrays and at run time for automatic arrays.
2.3: Example
Computing mean, median and mode
What is mean ?
Mean is same as average. The mean is found by adding up all of the given data
and dividing by the number of elements.
Example: Mean of 1,2,3,4,5 is
(1+2+3+4+5 )/5 = 15/3 = 3
What is Median ?
The median is the middle number in an ordered list (ascending or descending). First
you arrange the numbers in orders in ascending order, then you find the middle
number and save it as median
Example:
12345
Median is 3
What is Mode ?
Mode is the element which happens most number of time in the list. If no element
happens more than once, all elements are considered as mode.
Algorithm
1. Start
2. Declare an array a[20], sum =0,i=0,j=0,z=0
3. Read number of terms n
4. Repeat step 5 & 6 while (i<n)
5. sum=sum+a[i]
6. next i
7. mean=sum/n
8. if(n%2=0)
median=(a[n/2]+a[n/2-1])/2
else
median=a[n/2]
9. print mean and median
10. repeat step 11 & 12 when i=0 to n, j=0 to i
11. if a[i]=a[j], then b[i]++
12. if b[i]>z, then z=b[i]
13. For i=0 to n if b[i]=z, print b[i]
14. end
Program:
#include <stdio.h>
main()
{ int i,j,x,k=0,n,a[20],z=0,b[20];
float sum=0, t,mean,medn,mod;
printf(“\n Enter the no. of elements (Max 20)\n”);
TPGIT/CSE 6
CS8251 Dept of CSE Programming in C
scanf(“%d”,&n);
printf(“Enter the elements\n”);
for(i=0;i
{scan (“%d”,&a[i]);}
for(i=0;i
{sum=sum+a[i];}
printf(“Sum: %f”,sum);
mean=sum/n;
}
for(i=0;i
{ for (j=i+1;j
{ if (a[i]>a[j])
{ t=a[i];a[i]=a[j];a[j]=t; }
}
}
if (n%2==0)
medn=(a[n/2]+a[(n/2)-1])/2;
else
medn=a[n/2];
for(i=0;i
{ for ( j=0; j<i; j++ )
{ if (a[i]==a[j])
b[i]++;
}
}
for(i=0;i<n;i++)
{ if (b[i]>z)
z=b[i];
}
printf(“Mean :%f \n Median : %f \n Mean : “, mean, medn);
for I i=0; i<n; i++)
{ if (b[i]==z)
printf(“%d\t”, a[i]);
}
}
TPGIT/CSE 7
CS8251 Dept of CSE Programming in C
The following Figure illustrates a two dimensional array, matrix. The array contains
three rows and tree columns, so it is said to be a 3-by-3 array. In general, an array
with m rows and n columns is called an m-by-n array.
[0] [1] [2]
[0] 10
[1]
[2] 10
Every element in array matrix is identified by an element name of the form matrix[ i ][ j
]; matrix is the name of the array, and i and j are the subscripts that uniquely identify
each element in matrix . Notice that the names of the elements in the first row all have a
first subscript of 0; the names of the elements in the third column all have a second
subscript of 2.
In the case of Two-dimensional array, during declaration the maximum number of rows
and maximum number of column should be specified for processing all array elements.
The implementation of the array stores all the elements in a single contiguous block of
memory. The other possible implementation would be a combination of several distinct
one-dimensional arrays. That’s not how C does it. In memory, the array is arranged
with the elements of the rightmost index next to each other. In other words, matrix[1][1]
comes right before matrix[1][2] in memory.
The following array:
[0] [1] [2]
[0] 1 2 3
[1] 4 5 6
[2] 7 8 9
would be stored:
123456789
EXAMPLE :
1 #include<stdio.h>
2 #include<conio.h>
3 int main()
4{
5 int matrix [3][3],i,j,r,c;
6 clrscr();
7 printf(“Enter the order of matrix\n”);
8 scanf(“%d%d”,&r,&c);
9 printf(“Enter elements of %d * %d matrix \n”,r,c);
10 for(i=0;i<r;i++)
11 for(j=0;j<c;j++)
12 scanf(“%d”,&matrix[i][j]);
13 printf(“Given matrix:\n”);
14 for(i=0;i<r;i++)
15 {
16 for(j=0;j<c;j++)
17 printf(“%d\t”,matrix[i][j]);
18 printf(“\n”);
19 }
20 printf(“%d\t”,matrix[2][2]);
TPGIT/CSE 8
CS8251 Dept of CSE Programming in C
21 getch();
22 return 0;
23 }
Output :
Enter the order of matrix
2
2
Enter elements of 2*2 matrix
1
2
3
4
Given matrix :
1 2
3 4
2.5 Example
Matrix Operations (Addition, Scaling, Determinant and Transpose)
/* Write a Program to implement the following operations on the matrices :
1. Addition
2. Subtraction
3. Multiplication
4. Transpose */
#include<stdio.h>
#include<conio.h>
int main()
{
int m,n,a[20][20],b[20][20],i,j,sum[20][20],sub[20][20],opt,tr[20][20],opt1,ch,e,f;
printf("Note : For Addition or Subtraction , no. of rows and columns should be same
and for transpose of matrices , your first matrices entered should be the desired
matrices .\n");
printf("Enter the no. of rows: ");
scanf("%d",&m);
printf("Enter the no. of columns: ");
scanf("%d",&n);
printf("Enter the Data Elements of first matrices\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
} printf("Enter the no. of rows for second matrices: ");
scanf("%d",&e);
printf("Enter the no. of columns: ");
scanf("%d",&f);
printf("Enter the Data Elements of second matrices\n");
TPGIT/CSE 9
CS8251 Common to CSE & IT Programming in C
for(i=0;i<e;i++)
{
for(j=0;j<f;j++)
{
scanf("%d",&b[i][j]);
}
}
do
{
if(m==e&&n==f)
{
printf("Enter 1 for addtion or subtraction of matrices\n");
if(n==e){printf("Enter 2 for multiplication of matrices\n");}
printf("Enter 3 for transpose of first matrices\n");
}
else if(m!=n&&n==e)
{
printf("Enter 2 for multiplication of matrices\n");
printf("Enter 3 for transpose of first matrices\n");
}
else
{
printf("Enter 3 for transpose of first matrices\n");
}
scanf("%d",&ch);
switch(ch)
{
case 1 :
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
sum[i][j]=a[i][j]+b[i][j];
sub[i][j]=a[i][j]-b[i][j];
}
}
printf("Enter 1 for Addition or 2 for Subtraction: ");
scanf("%d",&opt);
switch(opt)
{
case 1 :
printf("The resultant matrices is :\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%3d",sum[i][j]);
}
break; }}
while(ch>0);
getch();
}
Actually, you do not place the null character at the end of a string constant. The C
compiler automatically places the '\0' at the end of the string when it initializes the
array. Let us try to print the above mentioned string −
#include <stdio.h>
int main () {
2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
3 strlen(s1);
Returns the length of string s1.
4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2;
greater than 0 if s1>s2.
5 strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in
string s1.
6 strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in
string s1.
The following example uses some of the above-mentioned functions −
#include <stdio.h>
#include <string.h>
int main () {
return 0;
}
When the above code is compiled and executed, it produces the following result −
strcpy( str3, str1) : Hello
Output:
Sorted array:
11 12 22 25 64
Time Complexity: O(n2) as there are two nested loops.
AuxiliarySpace: O(1)
The good thing about selection sort is it never makes more than O(n) swaps and can be
useful when memory write is a costly operation.
2.8 Binary Search
#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];
first = 0;
last = n - 1;
middle = (first+last)/2;
return 0;
}
Output of program:
int main()
{
int array[100], search, c, n;
return 0;
}
Output of program: