Unit - 3 Notes
Unit - 3 Notes
Syllabus:
Arrays- Initialization – Declaration One dimensional and Two dimensional arrays. String – String Operations –
String Arrays. Simple Programs – Sorting – Searching – Matrix Operations.
Introduction:
3.1 Arrays
#include<stdio.h>
#include<conio.h>
void main()
{
int mark1,mark2,mark3,mark4,mark5,tot;
clrscr();
printf("Enter the five subject marks of a student ");
scanf("%d %d %d",&mark1,&mark2,&mark3,&mark4,&mark5);
tot = mark1+mark2+mark3+mark4+mark5;
printf("Total = %d",tot);
}
Explanation
We have to obtain marks of five different and so we are using five different varaibles to obtain the marks.
Problem:
For example, consider a wild scenario where we have to obtain the marks of 100 different subjects.How we
could acheive this?
Solution :
We have to use 100 varibles like mark1, mark2, mark3, mark4,............., mark100.
3.1.1 Introduction
An array is just an identifier to store a set of data with common name. The same rules used to name a
variable is applicable for array varibles also.
Array is a collection or group of similar data type elements stored in contiguous memory.
Array is a derived data type that is used to store elements in contiguous memory location. Derived
data type is nothing but a data type formed from the primary data type.
Syntax
Data-Type ArrayName[index];
or
Storage_Class Data_Type ArrayName[index]
float a[100] means that ,it can store 100 floating point values in contiguous memory location.
int age[5];
The array age has five integer elements such as age[0], age[1], age[2], age[3], age[4].
The first element of array is numbered 0. i.e. age[0]. An array index always starts from zero.
Array index starts with 0 and ends with n-1. Where n is an size of an Array.
The size of array age is 10 bytes.i.e five times the size of integer, becuase the integer requires two bytes
and there are 5 integer elements in the array age.
The starting adress of array age is 1010 and the address of next element is 1012 and not 1011,because an
integer requires 2 bytes of memory, so both the address bytes 1010 and 1011 will be occupied by the
first element age[0] itself.
Initializing an array:
In the above example an array of size 20 bytes (10 elements each requiring 2 bytes.) will be allocated. In other
words an array with a memory to hold 10 integer variables will be created.
Array
marks[0] marks[1] marks[2] marks[3] marks[4] marks[5] marks[6] marks[7] marks[8] marks[9]
elements
The elements of an array which has not been initialized will have a garbage values.
In the above initialization, memory for ten elements has been created but, only 5 values have been
initialized, so the memory for the remaining five variables (10 bytes) will remain unused.
int marks[]={65,68,47,87,89};
In the above example, index has not been specified and so memory as big as to hold five variables(i.e. 10 bytes)
only will be created.
Value 65 68 47 87 89
By initializing the value without specifying the index is called auto arrays.
Example
int marks[4]=54;
Here the fifth element (index starts from 0) alone will be initialized and the value 89 will be replaced by 54.
#include<stdio.h>
void main()
{
int raja=21;
int mani=23;
int rajesh=25;
int ram=27;
int sam=29;
int paul=28;
int rani=26;
int peter=24;
int suresh=22;
int ramesh = 30;
int sum =0;
int avg;
sum = raja + mani + rajesh + ram + sam + paul + rani + peter + suresh +ramesh;
avg=(sum)/10;
printf("%d",avg);
}
Here we are using ten different variables and if we have to caclulate the average age of 1000 persons, then it
wuold be a tedious and time consiuming process.
#include<stdio.h>
void main()
{
int age[10]={21,23,25,27,29,28,26,24,22,30};
int sum=0;
int avg;
for(int i=0;i<10;i++)
{
sum=sum+age[i];
}
avg= (sum)/10;
printf("%d",avg);
}
Here we need not worry, even if we have to calculate the average age of 1,00,000 persons, because we are going
to make only minor change in the above program.i.e instead of using 10 we are going to use 1,00,000.
The program for calculating the average age of 1,00,000 persons will be like
#include<stdio.h>
void main()
{
int age[100000]={21,23,25,27,29,28,26,24,22,30};
int sum=0;
int avg;
for(int i=0;i<100000;i++)
{
sum=sum+age[i];
}
avg= (sum)/100000;
printf("%d",avg);
}
float price[12];
All the elements of an array will share the same variable name but they can be distinguished form each
other by using their index.For example
int marks[5];
Here all the five elements of the mark will share the same variable name marks, but they can be
distinguished from each other by their index like marks[0], marks[3] etc..
Any particular element of an array can be accessed or modified separately without disturbing the other
elements of the array.
The elements of an array can be assigned to another ordinary variable or array variable of its same data
type.
Example
12 45 26 11 33 22 44 15
12 45 26 11 33 22 44 26
45 45 26 11 33 22 44 15
12 22 26 11 33 22 44 15
But the below assignment is not possible hence an entire array cannot be assigned to a single variable.
b=a;//invalid
3.1.4 How Array is Stored
Consider, if an array has 100 elements and if one has to read and write all the 100 elements of an array, then it
will be a tedious and time consuming process as the program will contain 100 read and write statements as
follows.
For Reading,
When you observe the scanf()and printf() statements, only the index has been changing from the first statement
till the last statement.
So the N statements for reading and writing can be rewritten as a single statement as follows
Example Program
/* C program to find the total marks of five different subjects of a students using arrays */
#include <stdio.h>
void main()
{
int marks[10];
int i,n;
int sum=0;
printf("Enter number of subjects: ");
scanf("%d",&n);
for(i=0;i<n;++i)
{
printf("Enter marks of subject%d: ",i+1);
scanf("%d",&marks[i]);
sum+=marks[i]; //sum=sum+marks[i]
}
printf("total marks= %d",sum);
}
Output
Enter number of subjects: 4
Enter marks of subject1: 24
Enter marks of subject2: 45
Enter marks of subject3: 65
Enter marks of subject4: 45
total marks= 179
Definition
Syntax
Data_Type Array_Name[index1][index2];
or
Example 1
int temp[3][3]
Initilization
4 5 8
1 3 2
9 6 7
Initialization
OR
OR
int c[2][3]={1,3,0,-1,5,9};
Here the array c has two rows and three columns ant it will be represented as
1 3 0
-1 5 9
Now Consider the single dimensional array marks[5] which contains marks of
five different subjects.
marks[5] ={65,68,47,87,89};
Element
Value 65 68 47 87 89
Now assume that these five subject marks need to be stored for five different students, then another dimension
(two dimensions) would be required and the five different subject marks of five different students would be
stored in a matrix format, where columns would represent marks and rows will represent students.
marks[0]
65 68 47 87 89
student1
marks [1]
84 81 82 94 93
student2
marks [2]
78 79 61 87 82
student3
marks [3]
81 56 68 91 78
student4
marks [4]
46 48 64 66 82
student5
For an instance, marks[2][1]=79 means that, the mark of the student3 in subject2 is 79.
Let us see how to read and write elements in a two dimensional array for the above scenario.
For Reading
For Writing
void main()
{
int marks[10][10];
int i,j,m,n;
int sum1=0,sum2=0;
printf("Enter number of students: ");
scanf("%d",&m);
printf("Enter number of subjects: ");
scanf("%d",&n);
for(i=0;i<m;++i)
{
printf("\nEnter details of student%d:\n",i+1);
for(j=0;j<n;++j)
{
printf(" Enter marks of subject%d: ",j+1);
scanf("%d",&marks[i][j]);
sum2+=marks[i][j];
}
printf("\ntotal marks of student%d is %d\n",i+1,sum2);
sum1+=sum2;
sum2=0;//have to reset to use for next student
}
printf("\n\n\ttotal marks of all student is %d",sum1);
}
Output
Enter number of students: 3
Enter number of subjects: 5
#include <stdio.h>
#include <stdlib.h>
void main()
int i,j;
for(i=0;i<2;++i)
for(j=0;j<2;++j)
scanf("%d",&a[i][j]);
for(i=0;i<2;++i)
for(j=0;j<2;++j)
{
printf("Enter b[%d][%d]: ",i+1,j+1);
scanf("%d",&b[i][j]);
for(i=0;i<2;++i)
for(j=0;j<2;++j)
printf("\nSum Of Matrix:\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j)
printf("%d\t",c[i][j]);
Output
Enter the elements of 1st matrix
Enter a[1][1]: 1
Enter a[1][2]: 3
Enter a[2][1]: 5
Enter a[2][2]: 7
Enter b[1][1]: 2
Enter b[1][2]: 4
Enter b[2][1]: 6
Enter b[2][2]: 8
Sum Of Matrix:
3 7
11 15
Definition
Declaration
Example
marks[2][5][5];
marks[0]
Class1
marks[0]
65 68 47 87 89
student1
marks [1]
84 81 82 94 93
student2
marks [2]
78 96 61 87 82
student3
marks [3]
81 56 68 91 78
student4
marks [4]
46 48 64 66 82
student5
marks[1]
Class2
marks[0]
65 68 47 87 89
student1
marks [1]
84 81 82 94 93
student2
marks [2]
78 79 61 87 82
student3
marks [3]
81 56 68 91 78
student4
marks [4]
46 48 64 66 82
student5
For an instance, marks[0][2][1]=96 means that, the mark of the student3 from class1 in subject2 is
96
For marks[1][3][1]=79 means that, the mark of the student3 from class2 in subject2 is 79.
Here we use three for loops for reading and writing elements in a three dimensional array.
For Reading
scanf(“%d”,&marks[i][j][k]);
For Writing
{
printf(“%d”,marks[i][j][k]);
The outermost for loop executes for two times i.e for each class and the middle for loop executes for ten times
i.e for each student and the inner loop executes for 50 times i.e for each marks.
The printf() or scanf() statement will execute as many number of times as the inner for loop(50 times)
Example program:
#include <stdio.h>
#include <stdlib.h>
/* C program to find the total marks of five different subjects of three students belonging to two different
classes using three dimensional arrays */
void main()
int marks[10][10][10];
int i,j,k,l,m,n;
int sum1=0,sum2=0,sum3=0;
scanf("%d",&l);
scanf("%d",&m);
for(i=0;i<l;++i)
for(j=0;j<m;++j)
for(k=0;k<n;++k)
scanf("%d",&marks[i][j][k]);
sum3+=marks[i][j][k];
sum2+=sum3;
sum1+=sum2;
Output :
Multidimensional Array
Arrays having more than one dimensions are called as multi dimensional arrays.two and three dimensionla array
are called as multi dimensional array.However, usually multidimensional array will have more than three
dimensions.
Syntax :
Array is used for different verities of applications. Below are the some of the applications of array:
in CPU Scheduling
in Recursive Function
Array are very useful when we have to stores multiple data under single name with same data type.
A. Static Data
For Example, Character and Integer values can be stored inside separate array but cannot be stored in
an single array
1. Inserting element is very difficult because before inserting element in an array we have to create empty
space by shifting other elements one position ahead.
for example if we have to insert an element in position 5, then we have to shift all the elements starting
from position 5 ,to thier next position.
20 34 55 66 77 88
20 34 55 66 60 77 88
2. This operation is faster if the array size is smaller, but same operation will be more and more time
consuming and non-efficient in case of array with large size.
1. Deletion is not easy because the elements are stored in contiguous memory location.
2. If we have to delete element from the array empty space will be created and thus we need to fill the
space by moving elements up in the array.
for example if we have to delete an element in position 5, then we have to shift all the elements starting
from position 5 ,to thier previous position.
20 34 55 66 77 88
20 34 55 77 88
E. Bound Checking
1. If we specify the size of array as ‘N’ then we can access elements up to ‘N-1′ but in C if we try to access
elements after ‘N-1′ i.e Nth element or N+1th element then we does not get any error message.
2. Process of checking the extreme limit of array is called Bound Checking and C does not perform Bound
Checking.
3. If the array range exceeds then we will get garbage value as result.
F. Shortage of Memory
1. Memory can be allocated at compile time only and so, if after executing program we need more space
for storing additional information then we cannot allocate additional space at run time.
G. Wastage of Memory
1. Memory can be allocated at compile time only and so, if we are creating more space than what is
actually required at run-time , then unused space will be wasted.
3.2 String
We are creating array of character to create string. Suppose if we have to store the name of the person
containing N letters then those N characters are stored as character array containng N characteres.
'W','E','L','C','O','M','E'
= Size of 'a' +
= Size of 'm' +
= Size of 'i' +
= Size of 'l' +
= Size of 'n' +
= Size of 'a' +
= Size of 'd' +
= Size of 'u';
output:
tanu
Any character in the keyboard placed within the double quotes will be called as string
Example
“asdf”
“1234”
“#as$12”
A string can be declared as array of characters. Every string should end with a null character (‘\0’).
Syntax
String / Character Array Variable name has the same rules as naming the varaiable name.
Examples
char city[30];
char name[20];
char message[50];
Note: A Null character is a byte containing all zeros. A null character determines the end of a string. It
means that whenever the compiler sees a null character it assumes that it has reached the end of the
string.
Whenever we declare a String then it will contain garbage values inside it. We have to initialize String or
Character array before using it.
char name[4]=”hai”;
Array
name[0] name[1] name[2] name[3]
Element
Address 1000 1001 1002 1003
Value h a I /0
If the above table is noted we can see that the fourth character is null character, even though we intentionally
did not initialize that.
Note: The last character of an array will be initialized as zero even if we did not intentionally initialize it.
1. char name[4]=”hai”;
2. char name[4]={‘h’,’a’,’i’};
3. char name[4]={{‘h’},{‘a’},{‘i’}};
char name[3]={‘h’,’a’,’i’};
In the first declaration the index value is 3 which mean that the character array can store only two characters
and a null character. Since we have initialized three character values, there will be no space for the null
character and hence the compiler cannot detect the end of a string and so when we print the string it will contain
some garbage value.
In the second declaration there is enough space to accommodate three character values and a null character and
so there will not be any problem in printing the string.
So the index value of a string should be big enough to accommodate the character values as well as the null
character.
void main()
char name1[3]={‘a’,’b’,’c’};
printf(“%s\n”,name1);
printf(“%s\n”,name2);
The string name1 does not have enough space to accommodate null character and hence null character will not
be included in the string name1 and so the compiler will not detect the end of string name1 and it prints some
garbage value at the end
Output:
abcẰ
def
Whenever the Character variable is used in the expression then it can be Converted into Integer Value called
ASCII value.
Examples :
Manipulation
char x = 'a';
printf("%d",x); // it prints 97
char x = 'a';
Displaying the ASCII value of the next character in the alphabet[ Note that %d in Printf ]
char x = 'a' + 1 ;
char x = 'a' + 1;
printf("%d",x);
/* Display Result = 25
Displaying the character which has an equivalent ASCII value of the Difference between 2 Characters
[Note that %c in Printf ]
printf("%c",x);
/* Display Result = ↓
char string2[30]=”hai”;
char string1[30]=”hello”;
char string3[30]=”welcome”;
Example
strlen() Output
int main()
{ 5
char string1[20]="hello";
int k;
k=strlen(string1);
printf("%d",k);
return 0;
}
strcpy() Output
int main()
{ Hello
char string1[20]="hello";
char string2[10];
strcpy(string2,string1);
printf("%s",string2);
return 0;
}
strncpy() Output
int main()
{ He
char string1[20]="hello";
char string2[10];
strncpy(string2,string1,2);
printf("%s",string2);
return 0;
}
strcmp() Output
int main()
{ -1
char string1[20]="abc";
char string2[10]="ABC";
int a;
a=strcmp(string2,string1);
printf("%d",a);
return 0;
}
stricmp() Output
void main()
{ 0
char string1[20]="abc";
char string2[10]="ABC";
int a;
a=stricmp(string2,string1);
printf("%d",a);
return 0;
}
strncmp() Ouptut
void main()
{ 32
char string1[20]="Abcdgh";
char string2[10]="abcdgh"; Note:
int a; The difference between the ASCII value of
a(97) and A(65) are displayed
a=strncmp(string2,string1,4);
printf("%d",a);
return 0;
}
strnicmp() Output
void main()
{ 0
char string1[20]="abcdef";
char string2[10]="abcdgh"; Only the first four characters are compared
and they are equal. the remaining characters
int a;
are ignored
a=strnicmp(string2,string1,4);
printf("%d",a);
return 0;
}
strlwr() Ouptut
int main()
{ abcdef
char string1[20]="ABCDEF";
strlwr(string1);
printf("%s",string1);
return 0;
}
strupr() Ouptut
int main()
{ ABCDEF
char string1[20]="abcdef";
strupr(string1);
printf("%s",string1);
return 0;
}
strchr() Output
int main()
{ adam
char string1[20]="madam";
char *p;
p=strchr(string1,'a');
printf("%s",p);
return 0;
}
strrchr() Output
int main()
{ Am
char string1[20]="madam";
char *p;
p=strrchr(string1,'a');
printf("%s",p);
return 0;
}
strstr() Ouput
int main()
{ adam
char string1[20]="madam";
char string2[10]="ada"; Note: if the destination string is not found null
character will be returned
char *p;
p=strstr(string1,string2);
printf("%s",p);
return 0;
}
strcat() Output
int main()
{ i am fine
char string1[20]="i am ";
char string2[10]="fine";
strcat(string1,string2);
printf("%s",string1);
return 0;
}
strncat() Output
int main()
{ i am good
char string1[20]="i am ";
char string2[10]="good and fine";
strncat(string1,string2,4);
printf("%s",string1);
return 0;
}
strset() Output
int main()
{ $$$
char string1[20]="hai";
strset(string1,'$');
printf("%s",string1);
return 0;
}
strnset() Output
int main()
{ $$i
char string1[20]="hai";
strnset(string1,'$',2);
printf("%s",string1);
return 0;
}
strspn() Output
int main()
{ 5
char string1[20]="i am sam";
char string2[20]="i am ram"; Note: blank space is also counted as character.
int k;
k=strspn(string1,string2);
printf("%d",k);
return 0;
}
strpbrk() Output
int main()
{ tall and strong
char string1[30]="he is tall and strong";
char string2[30]="tall";
char *p;
p=strpbrk(string1,string2);
printf("%s",p);
return 0;
}
.